CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • ConsoleErrorHandler
  • ConsoleInput
  • ConsoleInputArgument
  • ConsoleInputOption
  • ConsoleInputSubcommand
  • ConsoleOptionParser
  • ConsoleOutput
  • HelpFormatter
  • Shell
  • ShellDispatcher
  • TaskCollection
   1: <?php
   2: /**
   3:  * Base class for Shells
   4:  *
   5:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
   6:  * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
   7:  *
   8:  * Licensed under The MIT License
   9:  * For full copyright and license information, please see the LICENSE.txt
  10:  * Redistributions of files must retain the above copyright notice.
  11:  *
  12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  13:  * @link          https://cakephp.org CakePHP(tm) Project
  14:  * @since         CakePHP(tm) v 1.2.0.5012
  15:  * @license       https://opensource.org/licenses/mit-license.php MIT License
  16:  */
  17: 
  18: App::uses('TaskCollection', 'Console');
  19: App::uses('ConsoleOutput', 'Console');
  20: App::uses('ConsoleInput', 'Console');
  21: App::uses('ConsoleInputSubcommand', 'Console');
  22: App::uses('ConsoleOptionParser', 'Console');
  23: App::uses('ClassRegistry', 'Utility');
  24: App::uses('File', 'Utility');
  25: 
  26: /**
  27:  * Base class for command-line utilities for automating programmer chores.
  28:  *
  29:  * @package       Cake.Console
  30:  */
  31: class Shell extends CakeObject {
  32: 
  33: /**
  34:  * Default error code
  35:  *
  36:  * @var int
  37:  */
  38:     const CODE_ERROR = 1;
  39: 
  40: /**
  41:  * Output constant making verbose shells.
  42:  *
  43:  * @var int
  44:  */
  45:     const VERBOSE = 2;
  46: 
  47: /**
  48:  * Output constant for making normal shells.
  49:  *
  50:  * @var int
  51:  */
  52:     const NORMAL = 1;
  53: 
  54: /**
  55:  * Output constants for making quiet shells.
  56:  *
  57:  * @var int
  58:  */
  59:     const QUIET = 0;
  60: 
  61: /**
  62:  * An instance of ConsoleOptionParser that has been configured for this class.
  63:  *
  64:  * @var ConsoleOptionParser
  65:  */
  66:     public $OptionParser;
  67: 
  68: /**
  69:  * If true, the script will ask for permission to perform actions.
  70:  *
  71:  * @var bool
  72:  */
  73:     public $interactive = true;
  74: 
  75: /**
  76:  * Contains command switches parsed from the command line.
  77:  *
  78:  * @var array
  79:  */
  80:     public $params = array();
  81: 
  82: /**
  83:  * The command (method/task) that is being run.
  84:  *
  85:  * @var string
  86:  */
  87:     public $command;
  88: 
  89: /**
  90:  * Contains arguments parsed from the command line.
  91:  *
  92:  * @var array
  93:  */
  94:     public $args = array();
  95: 
  96: /**
  97:  * The name of the shell in camelized.
  98:  *
  99:  * @var string
 100:  */
 101:     public $name = null;
 102: 
 103: /**
 104:  * The name of the plugin the shell belongs to.
 105:  * Is automatically set by ShellDispatcher when a shell is constructed.
 106:  *
 107:  * @var string
 108:  */
 109:     public $plugin = null;
 110: 
 111: /**
 112:  * Contains tasks to load and instantiate
 113:  *
 114:  * @var array
 115:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::$tasks
 116:  */
 117:     public $tasks = array();
 118: 
 119: /**
 120:  * Contains the loaded tasks
 121:  *
 122:  * @var array
 123:  */
 124:     public $taskNames = array();
 125: 
 126: /**
 127:  * Contains models to load and instantiate
 128:  *
 129:  * @var array
 130:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::$uses
 131:  */
 132:     public $uses = array();
 133: 
 134: /**
 135:  * This shell's primary model class name, the first model in the $uses property
 136:  *
 137:  * @var string
 138:  */
 139:     public $modelClass = null;
 140: 
 141: /**
 142:  * Task Collection for the command, used to create Tasks.
 143:  *
 144:  * @var TaskCollection
 145:  */
 146:     public $Tasks;
 147: 
 148: /**
 149:  * Normalized map of tasks.
 150:  *
 151:  * @var string
 152:  */
 153:     protected $_taskMap = array();
 154: 
 155: /**
 156:  * stdout object.
 157:  *
 158:  * @var ConsoleOutput
 159:  */
 160:     public $stdout;
 161: 
 162: /**
 163:  * stderr object.
 164:  *
 165:  * @var ConsoleOutput
 166:  */
 167:     public $stderr;
 168: 
 169: /**
 170:  * stdin object
 171:  *
 172:  * @var ConsoleInput
 173:  */
 174:     public $stdin;
 175: 
 176: /**
 177:  * The number of bytes last written to the output stream
 178:  * used when overwriting the previous message.
 179:  *
 180:  * @var int
 181:  */
 182:     protected $_lastWritten = 0;
 183: 
 184: /**
 185:  * Contains helpers which have been previously instantiated
 186:  *
 187:  * @var array
 188:  */
 189:     protected $_helpers = array();
 190: 
 191: /**
 192:  *  Constructs this Shell instance.
 193:  *
 194:  * @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
 195:  * @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
 196:  * @param ConsoleInput $stdin A ConsoleInput object for stdin.
 197:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell
 198:  */
 199:     public function __construct($stdout = null, $stderr = null, $stdin = null) {
 200:         if (!$this->name) {
 201:             $this->name = Inflector::camelize(str_replace(array('Shell', 'Task'), '', get_class($this)));
 202:         }
 203:         $this->Tasks = new TaskCollection($this);
 204: 
 205:         $this->stdout = $stdout ? $stdout : new ConsoleOutput('php://stdout');
 206:         $this->stderr = $stderr ? $stderr : new ConsoleOutput('php://stderr');
 207:         $this->stdin = $stdin ? $stdin : new ConsoleInput('php://stdin');
 208: 
 209:         $this->_useLogger();
 210:         $parent = get_parent_class($this);
 211:         if ($this->tasks !== null && $this->tasks !== false) {
 212:             $this->_mergeVars(array('tasks'), $parent, true);
 213:         }
 214:         if (!empty($this->uses)) {
 215:             $this->_mergeVars(array('uses'), $parent, false);
 216:         }
 217:     }
 218: 
 219: /**
 220:  * Initializes the Shell
 221:  * acts as constructor for subclasses
 222:  * allows configuration of tasks prior to shell execution
 223:  *
 224:  * @return void
 225:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::initialize
 226:  */
 227:     public function initialize() {
 228:         $this->_loadModels();
 229:         $this->loadTasks();
 230:     }
 231: 
 232: /**
 233:  * Starts up the Shell and displays the welcome message.
 234:  * Allows for checking and configuring prior to command or main execution
 235:  *
 236:  * Override this method if you want to remove the welcome information,
 237:  * or otherwise modify the pre-command flow.
 238:  *
 239:  * @return void
 240:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::startup
 241:  */
 242:     public function startup() {
 243:         $this->_welcome();
 244:     }
 245: 
 246: /**
 247:  * Displays a header for the shell
 248:  *
 249:  * @return void
 250:  */
 251:     protected function _welcome() {
 252:         $this->out();
 253:         $this->out(__d('cake_console', '<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
 254:         $this->hr();
 255:         $this->out(__d('cake_console', 'App : %s', APP_DIR));
 256:         $this->out(__d('cake_console', 'Path: %s', APP));
 257:         $this->hr();
 258:     }
 259: 
 260: /**
 261:  * If $uses is an array load each of the models in the array
 262:  *
 263:  * @return bool
 264:  */
 265:     protected function _loadModels() {
 266:         if (is_array($this->uses)) {
 267:             list(, $this->modelClass) = pluginSplit(current($this->uses));
 268:             foreach ($this->uses as $modelClass) {
 269:                 $this->loadModel($modelClass);
 270:             }
 271:         }
 272:         return true;
 273:     }
 274: 
 275: /**
 276:  * Lazy loads models using the loadModel() method if declared in $uses
 277:  *
 278:  * @param string $name The name of the model to look for.
 279:  * @return void
 280:  */
 281:     public function __isset($name) {
 282:         if (is_array($this->uses)) {
 283:             foreach ($this->uses as $modelClass) {
 284:                 list(, $class) = pluginSplit($modelClass);
 285:                 if ($name === $class) {
 286:                     return $this->loadModel($modelClass);
 287:                 }
 288:             }
 289:         }
 290:     }
 291: 
 292: /**
 293:  * Loads and instantiates models required by this shell.
 294:  *
 295:  * @param string $modelClass Name of model class to load
 296:  * @param mixed $id Initial ID the instanced model class should have
 297:  * @return mixed true when single model found and instance created, error returned if model not found.
 298:  * @throws MissingModelException if the model class cannot be found.
 299:  */
 300:     public function loadModel($modelClass = null, $id = null) {
 301:         if ($modelClass === null) {
 302:             $modelClass = $this->modelClass;
 303:         }
 304: 
 305:         $this->uses = ($this->uses) ? (array)$this->uses : array();
 306:         if (!in_array($modelClass, $this->uses)) {
 307:             $this->uses[] = $modelClass;
 308:         }
 309: 
 310:         list($plugin, $modelClass) = pluginSplit($modelClass, true);
 311:         if (!isset($this->modelClass)) {
 312:             $this->modelClass = $modelClass;
 313:         }
 314: 
 315:         $this->{$modelClass} = ClassRegistry::init(array(
 316:             'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
 317:         ));
 318:         if (!$this->{$modelClass}) {
 319:             throw new MissingModelException($modelClass);
 320:         }
 321:         return true;
 322:     }
 323: 
 324: /**
 325:  * Loads tasks defined in public $tasks
 326:  *
 327:  * @return bool
 328:  */
 329:     public function loadTasks() {
 330:         if ($this->tasks === true || empty($this->tasks) || empty($this->Tasks)) {
 331:             return true;
 332:         }
 333:         $this->_taskMap = TaskCollection::normalizeObjectArray((array)$this->tasks);
 334:         $this->taskNames = array_merge($this->taskNames, array_keys($this->_taskMap));
 335:         return true;
 336:     }
 337: 
 338: /**
 339:  * Check to see if this shell has a task with the provided name.
 340:  *
 341:  * @param string $task The task name to check.
 342:  * @return bool Success
 343:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasTask
 344:  */
 345:     public function hasTask($task) {
 346:         return isset($this->_taskMap[Inflector::camelize($task)]);
 347:     }
 348: 
 349: /**
 350:  * Check to see if this shell has a callable method by the given name.
 351:  *
 352:  * @param string $name The method name to check.
 353:  * @return bool
 354:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasMethod
 355:  */
 356:     public function hasMethod($name) {
 357:         try {
 358:             $method = new ReflectionMethod($this, $name);
 359:             if (!$method->isPublic() || substr($name, 0, 1) === '_') {
 360:                 return false;
 361:             }
 362:             if ($method->getDeclaringClass()->name === 'Shell') {
 363:                 return false;
 364:             }
 365:             return true;
 366:         } catch (ReflectionException $e) {
 367:             return false;
 368:         }
 369:     }
 370: 
 371: /**
 372:  * Dispatch a command to another Shell. Similar to CakeObject::requestAction()
 373:  * but intended for running shells from other shells.
 374:  *
 375:  * ### Usage:
 376:  *
 377:  * With a string command:
 378:  *
 379:  *  `return $this->dispatchShell('schema create DbAcl');`
 380:  *
 381:  * Avoid using this form if you have string arguments, with spaces in them.
 382:  * The dispatched will be invoked incorrectly. Only use this form for simple
 383:  * command dispatching.
 384:  *
 385:  * With an array command:
 386:  *
 387:  * `return $this->dispatchShell('schema', 'create', 'i18n', '--dry');`
 388:  *
 389:  * @return mixed The return of the other shell.
 390:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::dispatchShell
 391:  */
 392:     public function dispatchShell() {
 393:         $args = func_get_args();
 394:         if (is_string($args[0]) && count($args) === 1) {
 395:             $args = explode(' ', $args[0]);
 396:         }
 397: 
 398:         $Dispatcher = new ShellDispatcher($args, false);
 399:         return $Dispatcher->dispatch();
 400:     }
 401: 
 402: /**
 403:  * Runs the Shell with the provided argv.
 404:  *
 405:  * Delegates calls to Tasks and resolves methods inside the class. Commands are looked
 406:  * up with the following order:
 407:  *
 408:  * - Method on the shell.
 409:  * - Matching task name.
 410:  * - `main()` method.
 411:  *
 412:  * If a shell implements a `main()` method, all missing method calls will be sent to
 413:  * `main()` with the original method name in the argv.
 414:  *
 415:  * @param string $command The command name to run on this shell. If this argument is empty,
 416:  *   and the shell has a `main()` method, that will be called instead.
 417:  * @param array $argv Array of arguments to run the shell with. This array should be missing the shell name.
 418:  * @return int|bool
 419:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::runCommand
 420:  */
 421:     public function runCommand($command, $argv) {
 422:         $isTask = $this->hasTask($command);
 423:         $isMethod = $this->hasMethod($command);
 424:         $isMain = $this->hasMethod('main');
 425: 
 426:         if ($isTask || $isMethod && $command !== 'execute') {
 427:             array_shift($argv);
 428:         }
 429: 
 430:         $this->OptionParser = $this->getOptionParser();
 431:         try {
 432:             list($this->params, $this->args) = $this->OptionParser->parse($argv, $command);
 433:         } catch (ConsoleException $e) {
 434:             $this->err(__d('cake_console', '<error>Error:</error> %s', $e->getMessage()));
 435:             $this->out($this->OptionParser->help($command));
 436:             return false;
 437:         }
 438: 
 439:         if (!empty($this->params['quiet'])) {
 440:             $this->_useLogger(false);
 441:         }
 442:         if (!empty($this->params['plugin'])) {
 443:             CakePlugin::load($this->params['plugin']);
 444:         }
 445:         $this->command = $command;
 446:         if (!empty($this->params['help'])) {
 447:             return $this->_displayHelp($command);
 448:         }
 449: 
 450:         if (($isTask || $isMethod || $isMain) && $command !== 'execute') {
 451:             $this->startup();
 452:         }
 453: 
 454:         if ($isTask) {
 455:             $command = Inflector::camelize($command);
 456:             return $this->{$command}->runCommand('execute', $argv);
 457:         }
 458:         if ($isMethod) {
 459:             return $this->{$command}();
 460:         }
 461:         if ($isMain) {
 462:             return $this->main();
 463:         }
 464:         $this->out($this->OptionParser->help($command));
 465:         return false;
 466:     }
 467: 
 468: /**
 469:  * Display the help in the correct format
 470:  *
 471:  * @param string $command The command to get help for.
 472:  * @return int|bool
 473:  */
 474:     protected function _displayHelp($command) {
 475:         $format = 'text';
 476:         if (!empty($this->args[0]) && $this->args[0] === 'xml') {
 477:             $format = 'xml';
 478:             $this->stdout->outputAs(ConsoleOutput::RAW);
 479:         } else {
 480:             $this->_welcome();
 481:         }
 482:         return $this->out($this->OptionParser->help($command, $format));
 483:     }
 484: 
 485: /**
 486:  * Gets the option parser instance and configures it.
 487:  *
 488:  * By overriding this method you can configure the ConsoleOptionParser before returning it.
 489:  *
 490:  * @return ConsoleOptionParser
 491:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::getOptionParser
 492:  */
 493:     public function getOptionParser() {
 494:         $name = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
 495:         $parser = new ConsoleOptionParser($name);
 496:         return $parser;
 497:     }
 498: 
 499: /**
 500:  * Overload get for lazy building of tasks
 501:  *
 502:  * @param string $name The property name to access.
 503:  * @return Shell Object of Task
 504:  */
 505:     public function __get($name) {
 506:         if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
 507:             $properties = $this->_taskMap[$name];
 508:             $this->{$name} = $this->Tasks->load($properties['class'], $properties['settings']);
 509:             $this->{$name}->args =& $this->args;
 510:             $this->{$name}->params =& $this->params;
 511:             $this->{$name}->initialize();
 512:             $this->{$name}->loadTasks();
 513:         }
 514:         return $this->{$name};
 515:     }
 516: 
 517: /**
 518:  * Safely access the values in $this->params.
 519:  *
 520:  * @param string $name The name of the parameter to get.
 521:  * @return string|bool|null Value. Will return null if it doesn't exist.
 522:  */
 523:     public function param($name) {
 524:         if (!isset($this->params[$name])) {
 525:             return null;
 526:         }
 527:         return $this->params[$name];
 528:     }
 529: 
 530: /**
 531:  * Prompts the user for input, and returns it.
 532:  *
 533:  * @param string $prompt Prompt text.
 534:  * @param string|array $options Array or string of options.
 535:  * @param string $default Default input value.
 536:  * @return mixed Either the default value, or the user-provided input.
 537:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::in
 538:  */
 539:     public function in($prompt, $options = null, $default = null) {
 540:         if (!$this->interactive) {
 541:             return $default;
 542:         }
 543:         $originalOptions = $options;
 544:         $in = $this->_getInput($prompt, $originalOptions, $default);
 545: 
 546:         if ($options && is_string($options)) {
 547:             if (strpos($options, ',')) {
 548:                 $options = explode(',', $options);
 549:             } elseif (strpos($options, '/')) {
 550:                 $options = explode('/', $options);
 551:             } else {
 552:                 $options = array($options);
 553:             }
 554:         }
 555:         if (is_array($options)) {
 556:             $options = array_merge(
 557:                 array_map('strtolower', $options),
 558:                 array_map('strtoupper', $options),
 559:                 $options
 560:             );
 561:             while ($in === '' || !in_array($in, $options)) {
 562:                 $in = $this->_getInput($prompt, $originalOptions, $default);
 563:             }
 564:         }
 565:         return $in;
 566:     }
 567: 
 568: /**
 569:  * Prompts the user for input, and returns it.
 570:  *
 571:  * @param string $prompt Prompt text.
 572:  * @param string|array $options Array or string of options.
 573:  * @param string $default Default input value.
 574:  * @return string|int the default value, or the user-provided input.
 575:  */
 576:     protected function _getInput($prompt, $options, $default) {
 577:         if (!is_array($options)) {
 578:             $printOptions = '';
 579:         } else {
 580:             $printOptions = '(' . implode('/', $options) . ')';
 581:         }
 582: 
 583:         if ($default === null) {
 584:             $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . '> ', 0);
 585:         } else {
 586:             $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . "[$default] > ", 0);
 587:         }
 588:         $result = $this->stdin->read();
 589: 
 590:         if ($result === false) {
 591:             $this->_stop(self::CODE_ERROR);
 592:             return self::CODE_ERROR;
 593:         }
 594:         $result = trim($result);
 595: 
 596:         if ($default !== null && ($result === '' || $result === null)) {
 597:             return $default;
 598:         }
 599:         return $result;
 600:     }
 601: 
 602: /**
 603:  * Wrap a block of text.
 604:  * Allows you to set the width, and indenting on a block of text.
 605:  *
 606:  * ### Options
 607:  *
 608:  * - `width` The width to wrap to. Defaults to 72
 609:  * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
 610:  * - `indent` Indent the text with the string provided. Defaults to null.
 611:  *
 612:  * @param string $text Text the text to format.
 613:  * @param string|int|array $options Array of options to use, or an integer to wrap the text to.
 614:  * @return string Wrapped / indented text
 615:  * @see CakeText::wrap()
 616:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapText
 617:  */
 618:     public function wrapText($text, $options = array()) {
 619:         return CakeText::wrap($text, $options);
 620:     }
 621: 
 622: /**
 623:  * Outputs a single or multiple messages to stdout. If no parameters
 624:  * are passed outputs just a newline.
 625:  *
 626:  * ### Output levels
 627:  *
 628:  * There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE.
 629:  * The verbose and quiet output levels, map to the `verbose` and `quiet` output switches
 630:  * present in most shells. Using Shell::QUIET for a message means it will always display.
 631:  * While using Shell::VERBOSE means it will only display when verbose output is toggled.
 632:  *
 633:  * @param string|array $message A string or an array of strings to output
 634:  * @param int $newlines Number of newlines to append
 635:  * @param int $level The message's output level, see above.
 636:  * @return int|bool Returns the number of bytes returned from writing to stdout.
 637:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::out
 638:  */
 639:     public function out($message = null, $newlines = 1, $level = Shell::NORMAL) {
 640:         $currentLevel = Shell::NORMAL;
 641:         if (!empty($this->params['verbose'])) {
 642:             $currentLevel = Shell::VERBOSE;
 643:         }
 644:         if (!empty($this->params['quiet'])) {
 645:             $currentLevel = Shell::QUIET;
 646:         }
 647:         if ($level <= $currentLevel) {
 648:             $this->_lastWritten = $this->stdout->write($message, $newlines);
 649:             return $this->_lastWritten;
 650:         }
 651:         return true;
 652:     }
 653: 
 654: /**
 655:  * Overwrite some already output text.
 656:  *
 657:  * Useful for building progress bars, or when you want to replace
 658:  * text already output to the screen with new text.
 659:  *
 660:  * **Warning** You cannot overwrite text that contains newlines.
 661:  *
 662:  * @param array|string $message The message to output.
 663:  * @param int $newlines Number of newlines to append.
 664:  * @param int $size The number of bytes to overwrite. Defaults to the length of the last message output.
 665:  * @return int|bool Returns the number of bytes returned from writing to stdout.
 666:  */
 667:     public function overwrite($message, $newlines = 1, $size = null) {
 668:         $size = $size ? $size : $this->_lastWritten;
 669: 
 670:         // Output backspaces.
 671:         $this->out(str_repeat("\x08", $size), 0);
 672: 
 673:         $newBytes = $this->out($message, 0);
 674: 
 675:         // Fill any remaining bytes with spaces.
 676:         $fill = $size - $newBytes;
 677:         if ($fill > 0) {
 678:             $this->out(str_repeat(' ', $fill), 0);
 679:         }
 680:         if ($newlines) {
 681:             $this->out($this->nl($newlines), 0);
 682:         }
 683:     }
 684: 
 685: /**
 686:  * Outputs a single or multiple error messages to stderr. If no parameters
 687:  * are passed outputs just a newline.
 688:  *
 689:  * @param string|array $message A string or an array of strings to output
 690:  * @param int $newlines Number of newlines to append
 691:  * @return void
 692:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::err
 693:  */
 694:     public function err($message = null, $newlines = 1) {
 695:         $this->stderr->write($message, $newlines);
 696:     }
 697: 
 698: /**
 699:  * Returns a single or multiple linefeeds sequences.
 700:  *
 701:  * @param int $multiplier Number of times the linefeed sequence should be repeated
 702:  * @return string
 703:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nl
 704:  */
 705:     public function nl($multiplier = 1) {
 706:         return str_repeat(ConsoleOutput::LF, $multiplier);
 707:     }
 708: 
 709: /**
 710:  * Outputs a series of minus characters to the standard output, acts as a visual separator.
 711:  *
 712:  * @param int $newlines Number of newlines to pre- and append
 713:  * @param int $width Width of the line, defaults to 63
 714:  * @return void
 715:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hr
 716:  */
 717:     public function hr($newlines = 0, $width = 63) {
 718:         $this->out(null, $newlines);
 719:         $this->out(str_repeat('-', $width));
 720:         $this->out(null, $newlines);
 721:     }
 722: 
 723: /**
 724:  * Displays a formatted error message
 725:  * and exits the application with status code 1
 726:  *
 727:  * @param string $title Title of the error
 728:  * @param string $message An optional error message
 729:  * @return int
 730:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::error
 731:  */
 732:     public function error($title, $message = null) {
 733:         $this->err(__d('cake_console', '<error>Error:</error> %s', $title));
 734: 
 735:         if (!empty($message)) {
 736:             $this->err($message);
 737:         }
 738:         $this->_stop(self::CODE_ERROR);
 739:         return self::CODE_ERROR;
 740:     }
 741: 
 742: /**
 743:  * Clear the console
 744:  *
 745:  * @return void
 746:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clear
 747:  */
 748:     public function clear() {
 749:         if (empty($this->params['noclear'])) {
 750:             if (DS === '/') {
 751:                 passthru('clear');
 752:             } else {
 753:                 passthru('cls');
 754:             }
 755:         }
 756:     }
 757: 
 758: /**
 759:  * Creates a file at given path
 760:  *
 761:  * @param string $path Where to put the file.
 762:  * @param string $contents Content to put in the file.
 763:  * @return bool Success
 764:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile
 765:  */
 766:     public function createFile($path, $contents) {
 767:         $this->out();
 768: 
 769:         if (is_file($path) && empty($this->params['force']) && $this->interactive === true) {
 770:             $this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
 771:             $key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
 772: 
 773:             if (strtolower($key) === 'q') {
 774:                 $this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
 775:                 $this->_stop();
 776:                 return true;
 777:             } elseif (strtolower($key) !== 'y') {
 778:                 $this->out(__d('cake_console', 'Skip `%s`', $path), 2);
 779:                 return false;
 780:             }
 781:         } else {
 782:             $this->out(__d('cake_console', 'Creating file %s', $path));
 783:         }
 784: 
 785:         $File = new File($path, true);
 786:         if ($File->exists() && $File->writable()) {
 787:             $data = $File->prepare($contents);
 788:             $File->write($data);
 789:             $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
 790:             return true;
 791:         }
 792: 
 793:         $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
 794:         return false;
 795:     }
 796: 
 797: /**
 798:  * Load given shell helper class
 799:  *
 800:  * @param string $name Name of the helper class. Supports plugin syntax.
 801:  * @return BaseShellHelper Instance of helper class
 802:  * @throws RuntimeException If invalid class name is provided
 803:  */
 804:     public function helper($name) {
 805:         if (isset($this->_helpers[$name])) {
 806:             return $this->_helpers[$name];
 807:         }
 808:         list($plugin, $helperClassName) = pluginSplit($name, true);
 809:         $helperClassNameShellHelper = Inflector::camelize($helperClassName) . "ShellHelper";
 810:         App::uses($helperClassNameShellHelper, $plugin . "Console/Helper");
 811:         if (!class_exists($helperClassNameShellHelper)) {
 812:             throw new RuntimeException("Class " . $helperClassName . " not found");
 813:         }
 814:         $helper = new $helperClassNameShellHelper($this->stdout);
 815:         $this->_helpers[$name] = $helper;
 816:         return $helper;
 817:     }
 818: 
 819: /**
 820:  * Action to create a Unit Test
 821:  *
 822:  * @return bool Success
 823:  */
 824:     protected function _checkUnitTest() {
 825:         if (class_exists('PHPUnit_Framework_TestCase')) {
 826:             return true;
 827:             //@codingStandardsIgnoreStart
 828:         } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
 829:             //@codingStandardsIgnoreEnd
 830:             return true;
 831:         } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
 832:             return true;
 833:         }
 834: 
 835:         $prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?');
 836:         $unitTest = $this->in($prompt, array('y', 'n'), 'y');
 837:         $result = strtolower($unitTest) === 'y' || strtolower($unitTest) === 'yes';
 838: 
 839:         if ($result) {
 840:             $this->out();
 841:             $this->out(__d('cake_console', 'You can download PHPUnit from %s', 'http://phpunit.de'));
 842:         }
 843:         return $result;
 844:     }
 845: 
 846: /**
 847:  * Makes absolute file path easier to read
 848:  *
 849:  * @param string $file Absolute file path
 850:  * @return string short path
 851:  * @link https://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPath
 852:  */
 853:     public function shortPath($file) {
 854:         $shortPath = str_replace(ROOT, null, $file);
 855:         $shortPath = str_replace('..' . DS, '', $shortPath);
 856:         return str_replace(DS . DS, DS, $shortPath);
 857:     }
 858: 
 859: /**
 860:  * Creates the proper controller path for the specified controller class name
 861:  *
 862:  * @param string $name Controller class name
 863:  * @return string Path to controller
 864:  */
 865:     protected function _controllerPath($name) {
 866:         return Inflector::underscore($name);
 867:     }
 868: 
 869: /**
 870:  * Creates the proper controller plural name for the specified controller class name
 871:  *
 872:  * @param string $name Controller class name
 873:  * @return string Controller plural name
 874:  */
 875:     protected function _controllerName($name) {
 876:         return Inflector::pluralize(Inflector::camelize($name));
 877:     }
 878: 
 879: /**
 880:  * Creates the proper model camelized name (singularized) for the specified name
 881:  *
 882:  * @param string $name Name
 883:  * @return string Camelized and singularized model name
 884:  */
 885:     protected function _modelName($name) {
 886:         return Inflector::camelize(Inflector::singularize($name));
 887:     }
 888: 
 889: /**
 890:  * Creates the proper underscored model key for associations
 891:  *
 892:  * @param string $name Model class name
 893:  * @return string Singular model key
 894:  */
 895:     protected function _modelKey($name) {
 896:         return Inflector::underscore($name) . '_id';
 897:     }
 898: 
 899: /**
 900:  * Creates the proper model name from a foreign key
 901:  *
 902:  * @param string $key Foreign key
 903:  * @return string Model name
 904:  */
 905:     protected function _modelNameFromKey($key) {
 906:         return Inflector::camelize(str_replace('_id', '', $key));
 907:     }
 908: 
 909: /**
 910:  * creates the singular name for use in views.
 911:  *
 912:  * @param string $name The plural underscored value.
 913:  * @return string name
 914:  */
 915:     protected function _singularName($name) {
 916:         return Inflector::variable(Inflector::singularize($name));
 917:     }
 918: 
 919: /**
 920:  * Creates the plural name for views
 921:  *
 922:  * @param string $name Name to use
 923:  * @return string Plural name for views
 924:  */
 925:     protected function _pluralName($name) {
 926:         return Inflector::variable(Inflector::pluralize($name));
 927:     }
 928: 
 929: /**
 930:  * Creates the singular human name used in views
 931:  *
 932:  * @param string $name Controller name
 933:  * @return string Singular human name
 934:  */
 935:     protected function _singularHumanName($name) {
 936:         return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
 937:     }
 938: 
 939: /**
 940:  * Creates the plural human name used in views
 941:  *
 942:  * @param string $name Controller name
 943:  * @return string Plural human name
 944:  */
 945:     protected function _pluralHumanName($name) {
 946:         return Inflector::humanize(Inflector::underscore($name));
 947:     }
 948: 
 949: /**
 950:  * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
 951:  *
 952:  * @param string $pluginName Name of the plugin you want ie. DebugKit
 953:  * @return string path path to the correct plugin.
 954:  */
 955:     protected function _pluginPath($pluginName) {
 956:         if (CakePlugin::loaded($pluginName)) {
 957:             return CakePlugin::path($pluginName);
 958:         }
 959:         return current(App::path('plugins')) . $pluginName . DS;
 960:     }
 961: 
 962: /**
 963:  * Used to enable or disable logging stream output to stdout and stderr
 964:  * If you don't wish to see in your stdout or stderr everything that is logged
 965:  * through CakeLog, call this function with first param as false
 966:  *
 967:  * @param bool $enable whether to enable CakeLog output or not
 968:  * @return void
 969:  */
 970:     protected function _useLogger($enable = true) {
 971:         if (!$enable) {
 972:             CakeLog::drop('stdout');
 973:             CakeLog::drop('stderr');
 974:             return;
 975:         }
 976:         if (!$this->_loggerIsConfigured("stdout")) {
 977:             $this->_configureStdOutLogger();
 978:         }
 979:         if (!$this->_loggerIsConfigured("stderr")) {
 980:             $this->_configureStdErrLogger();
 981:         }
 982:     }
 983: 
 984: /**
 985:  * Configure the stdout logger
 986:  * 
 987:  * @return void
 988:  */
 989:     protected function _configureStdOutLogger() {
 990:         CakeLog::config('stdout', array(
 991:             'engine' => 'Console',
 992:             'types' => array('notice', 'info'),
 993:             'stream' => $this->stdout,
 994:         ));
 995:     }
 996: 
 997: /**
 998:  * Configure the stderr logger
 999:  * 
1000:  * @return void
1001:  */
1002:     protected function _configureStdErrLogger() {
1003:         CakeLog::config('stderr', array(
1004:             'engine' => 'Console',
1005:             'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'),
1006:             'stream' => $this->stderr,
1007:         ));
1008:     }
1009: 
1010: /**
1011:  * Checks if the given logger is configured
1012:  * 
1013:  * @param string $logger The name of the logger to check 
1014:  * @return bool
1015:  */
1016:     protected function _loggerIsConfigured($logger) {
1017:         $configured = CakeLog::configured();
1018:         return in_array($logger, $configured);
1019:     }
1020: }
1021: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs