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.9 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.9
      • 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 (http://cakephp.org)
   6:  * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  13:  * @link          http://cakephp.org CakePHP(tm) Project
  14:  * @since         CakePHP(tm) v 1.2.0.5012
  15:  * @license       http://www.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 http://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 http://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 http://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 http://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 http://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 http://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 http://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 http://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 void
 419:  * @link http://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->out($this->OptionParser->help($command));
 435:             return false;
 436:         }
 437: 
 438:         if (!empty($this->params['quiet'])) {
 439:             $this->_useLogger(false);
 440:         }
 441:         if (!empty($this->params['plugin'])) {
 442:             CakePlugin::load($this->params['plugin']);
 443:         }
 444:         $this->command = $command;
 445:         if (!empty($this->params['help'])) {
 446:             return $this->_displayHelp($command);
 447:         }
 448: 
 449:         if (($isTask || $isMethod || $isMain) && $command !== 'execute') {
 450:             $this->startup();
 451:         }
 452: 
 453:         if ($isTask) {
 454:             $command = Inflector::camelize($command);
 455:             return $this->{$command}->runCommand('execute', $argv);
 456:         }
 457:         if ($isMethod) {
 458:             return $this->{$command}();
 459:         }
 460:         if ($isMain) {
 461:             return $this->main();
 462:         }
 463:         $this->out($this->OptionParser->help($command));
 464:         return false;
 465:     }
 466: 
 467: /**
 468:  * Display the help in the correct format
 469:  *
 470:  * @param string $command The command to get help for.
 471:  * @return void
 472:  */
 473:     protected function _displayHelp($command) {
 474:         $format = 'text';
 475:         if (!empty($this->args[0]) && $this->args[0] === 'xml') {
 476:             $format = 'xml';
 477:             $this->stdout->outputAs(ConsoleOutput::RAW);
 478:         } else {
 479:             $this->_welcome();
 480:         }
 481:         return $this->out($this->OptionParser->help($command, $format));
 482:     }
 483: 
 484: /**
 485:  * Gets the option parser instance and configures it.
 486:  *
 487:  * By overriding this method you can configure the ConsoleOptionParser before returning it.
 488:  *
 489:  * @return ConsoleOptionParser
 490:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::getOptionParser
 491:  */
 492:     public function getOptionParser() {
 493:         $name = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
 494:         $parser = new ConsoleOptionParser($name);
 495:         return $parser;
 496:     }
 497: 
 498: /**
 499:  * Overload get for lazy building of tasks
 500:  *
 501:  * @param string $name The property name to access.
 502:  * @return Shell Object of Task
 503:  */
 504:     public function __get($name) {
 505:         if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
 506:             $properties = $this->_taskMap[$name];
 507:             $this->{$name} = $this->Tasks->load($properties['class'], $properties['settings']);
 508:             $this->{$name}->args =& $this->args;
 509:             $this->{$name}->params =& $this->params;
 510:             $this->{$name}->initialize();
 511:             $this->{$name}->loadTasks();
 512:         }
 513:         return $this->{$name};
 514:     }
 515: 
 516: /**
 517:  * Safely access the values in $this->params.
 518:  *
 519:  * @param string $name The name of the parameter to get.
 520:  * @return string|bool|null Value. Will return null if it doesn't exist.
 521:  */
 522:     public function param($name) {
 523:         if (!isset($this->params[$name])) {
 524:             return null;
 525:         }
 526:         return $this->params[$name];
 527:     }
 528: 
 529: /**
 530:  * Prompts the user for input, and returns it.
 531:  *
 532:  * @param string $prompt Prompt text.
 533:  * @param string|array $options Array or string of options.
 534:  * @param string $default Default input value.
 535:  * @return mixed Either the default value, or the user-provided input.
 536:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::in
 537:  */
 538:     public function in($prompt, $options = null, $default = null) {
 539:         if (!$this->interactive) {
 540:             return $default;
 541:         }
 542:         $originalOptions = $options;
 543:         $in = $this->_getInput($prompt, $originalOptions, $default);
 544: 
 545:         if ($options && is_string($options)) {
 546:             if (strpos($options, ',')) {
 547:                 $options = explode(',', $options);
 548:             } elseif (strpos($options, '/')) {
 549:                 $options = explode('/', $options);
 550:             } else {
 551:                 $options = array($options);
 552:             }
 553:         }
 554:         if (is_array($options)) {
 555:             $options = array_merge(
 556:                 array_map('strtolower', $options),
 557:                 array_map('strtoupper', $options),
 558:                 $options
 559:             );
 560:             while ($in === '' || !in_array($in, $options)) {
 561:                 $in = $this->_getInput($prompt, $originalOptions, $default);
 562:             }
 563:         }
 564:         return $in;
 565:     }
 566: 
 567: /**
 568:  * Prompts the user for input, and returns it.
 569:  *
 570:  * @param string $prompt Prompt text.
 571:  * @param string|array $options Array or string of options.
 572:  * @param string $default Default input value.
 573:  * @return Either the default value, or the user-provided input.
 574:  */
 575:     protected function _getInput($prompt, $options, $default) {
 576:         if (!is_array($options)) {
 577:             $printOptions = '';
 578:         } else {
 579:             $printOptions = '(' . implode('/', $options) . ')';
 580:         }
 581: 
 582:         if ($default === null) {
 583:             $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . '> ', 0);
 584:         } else {
 585:             $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . "[$default] > ", 0);
 586:         }
 587:         $result = $this->stdin->read();
 588: 
 589:         if ($result === false) {
 590:             $this->_stop(self::CODE_ERROR);
 591:             return self::CODE_ERROR;
 592:         }
 593:         $result = trim($result);
 594: 
 595:         if ($default !== null && ($result === '' || $result === null)) {
 596:             return $default;
 597:         }
 598:         return $result;
 599:     }
 600: 
 601: /**
 602:  * Wrap a block of text.
 603:  * Allows you to set the width, and indenting on a block of text.
 604:  *
 605:  * ### Options
 606:  *
 607:  * - `width` The width to wrap to. Defaults to 72
 608:  * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
 609:  * - `indent` Indent the text with the string provided. Defaults to null.
 610:  *
 611:  * @param string $text Text the text to format.
 612:  * @param string|int|array $options Array of options to use, or an integer to wrap the text to.
 613:  * @return string Wrapped / indented text
 614:  * @see CakeText::wrap()
 615:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapText
 616:  */
 617:     public function wrapText($text, $options = array()) {
 618:         return CakeText::wrap($text, $options);
 619:     }
 620: 
 621: /**
 622:  * Outputs a single or multiple messages to stdout. If no parameters
 623:  * are passed outputs just a newline.
 624:  *
 625:  * ### Output levels
 626:  *
 627:  * There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE.
 628:  * The verbose and quiet output levels, map to the `verbose` and `quiet` output switches
 629:  * present in most shells. Using Shell::QUIET for a message means it will always display.
 630:  * While using Shell::VERBOSE means it will only display when verbose output is toggled.
 631:  *
 632:  * @param string|array $message A string or an array of strings to output
 633:  * @param int $newlines Number of newlines to append
 634:  * @param int $level The message's output level, see above.
 635:  * @return int|bool Returns the number of bytes returned from writing to stdout.
 636:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::out
 637:  */
 638:     public function out($message = null, $newlines = 1, $level = Shell::NORMAL) {
 639:         $currentLevel = Shell::NORMAL;
 640:         if (!empty($this->params['verbose'])) {
 641:             $currentLevel = Shell::VERBOSE;
 642:         }
 643:         if (!empty($this->params['quiet'])) {
 644:             $currentLevel = Shell::QUIET;
 645:         }
 646:         if ($level <= $currentLevel) {
 647:             $this->_lastWritten = $this->stdout->write($message, $newlines);
 648:             return $this->_lastWritten;
 649:         }
 650:         return true;
 651:     }
 652: 
 653: /**
 654:  * Overwrite some already output text.
 655:  *
 656:  * Useful for building progress bars, or when you want to replace
 657:  * text already output to the screen with new text.
 658:  *
 659:  * **Warning** You cannot overwrite text that contains newlines.
 660:  *
 661:  * @param array|string $message The message to output.
 662:  * @param int $newlines Number of newlines to append.
 663:  * @param int $size The number of bytes to overwrite. Defaults to the length of the last message output.
 664:  * @return int|bool Returns the number of bytes returned from writing to stdout.
 665:  */
 666:     public function overwrite($message, $newlines = 1, $size = null) {
 667:         $size = $size ? $size : $this->_lastWritten;
 668: 
 669:         // Output backspaces.
 670:         $this->out(str_repeat("\x08", $size), 0);
 671: 
 672:         $newBytes = $this->out($message, 0);
 673: 
 674:         // Fill any remaining bytes with spaces.
 675:         $fill = $size - $newBytes;
 676:         if ($fill > 0) {
 677:             $this->out(str_repeat(' ', $fill), 0);
 678:         }
 679:         if ($newlines) {
 680:             $this->out($this->nl($newlines), 0);
 681:         }
 682:     }
 683: 
 684: /**
 685:  * Outputs a single or multiple error messages to stderr. If no parameters
 686:  * are passed outputs just a newline.
 687:  *
 688:  * @param string|array $message A string or an array of strings to output
 689:  * @param int $newlines Number of newlines to append
 690:  * @return void
 691:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::err
 692:  */
 693:     public function err($message = null, $newlines = 1) {
 694:         $this->stderr->write($message, $newlines);
 695:     }
 696: 
 697: /**
 698:  * Returns a single or multiple linefeeds sequences.
 699:  *
 700:  * @param int $multiplier Number of times the linefeed sequence should be repeated
 701:  * @return string
 702:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nl
 703:  */
 704:     public function nl($multiplier = 1) {
 705:         return str_repeat(ConsoleOutput::LF, $multiplier);
 706:     }
 707: 
 708: /**
 709:  * Outputs a series of minus characters to the standard output, acts as a visual separator.
 710:  *
 711:  * @param int $newlines Number of newlines to pre- and append
 712:  * @param int $width Width of the line, defaults to 63
 713:  * @return void
 714:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hr
 715:  */
 716:     public function hr($newlines = 0, $width = 63) {
 717:         $this->out(null, $newlines);
 718:         $this->out(str_repeat('-', $width));
 719:         $this->out(null, $newlines);
 720:     }
 721: 
 722: /**
 723:  * Displays a formatted error message
 724:  * and exits the application with status code 1
 725:  *
 726:  * @param string $title Title of the error
 727:  * @param string $message An optional error message
 728:  * @return void
 729:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::error
 730:  */
 731:     public function error($title, $message = null) {
 732:         $this->err(__d('cake_console', '<error>Error:</error> %s', $title));
 733: 
 734:         if (!empty($message)) {
 735:             $this->err($message);
 736:         }
 737:         $this->_stop(self::CODE_ERROR);
 738:         return self::CODE_ERROR;
 739:     }
 740: 
 741: /**
 742:  * Clear the console
 743:  *
 744:  * @return void
 745:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clear
 746:  */
 747:     public function clear() {
 748:         if (empty($this->params['noclear'])) {
 749:             if (DS === '/') {
 750:                 passthru('clear');
 751:             } else {
 752:                 passthru('cls');
 753:             }
 754:         }
 755:     }
 756: 
 757: /**
 758:  * Creates a file at given path
 759:  *
 760:  * @param string $path Where to put the file.
 761:  * @param string $contents Content to put in the file.
 762:  * @return bool Success
 763:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile
 764:  */
 765:     public function createFile($path, $contents) {
 766:         $path = str_replace(DS . DS, DS, $path);
 767: 
 768:         $this->out();
 769: 
 770:         if (is_file($path) && empty($this->params['force']) && $this->interactive === true) {
 771:             $this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
 772:             $key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
 773: 
 774:             if (strtolower($key) === 'q') {
 775:                 $this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
 776:                 $this->_stop();
 777:                 return true;
 778:             } elseif (strtolower($key) !== 'y') {
 779:                 $this->out(__d('cake_console', 'Skip `%s`', $path), 2);
 780:                 return false;
 781:             }
 782:         } else {
 783:             $this->out(__d('cake_console', 'Creating file %s', $path));
 784:         }
 785: 
 786:         $File = new File($path, true);
 787:         if ($File->exists() && $File->writable()) {
 788:             $data = $File->prepare($contents);
 789:             $File->write($data);
 790:             $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
 791:             return true;
 792:         }
 793: 
 794:         $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
 795:         return false;
 796:     }
 797: 
 798: /**
 799:  * Load given shell helper class
 800:  *
 801:  * @param string $name Name of the helper class. Supports plugin syntax.
 802:  * @return BaseShellHelper Instance of helper class
 803:  * @throws RuntimeException If invalid class name is provided
 804:  */
 805:     public function helper($name) {
 806:         if (isset($this->_helpers[$name])) {
 807:             return $this->_helpers[$name];
 808:         }
 809:         list($plugin, $helperClassName) = pluginSplit($name, true);
 810:         $helperClassName = Inflector::camelize($name) . "ShellHelper";
 811:         App::uses($helperClassName, $plugin . "Console/Helper");
 812:         if (!class_exists($helperClassName)) {
 813:             throw new RuntimeException("Class " . $helperClassName . " not found");
 814:         }
 815:         $helper = new $helperClassName($this->stdout);
 816:         $this->_helpers[$name] = $helper;
 817:         return $helper;
 818:     }
 819: 
 820: /**
 821:  * Action to create a Unit Test
 822:  *
 823:  * @return bool Success
 824:  */
 825:     protected function _checkUnitTest() {
 826:         if (class_exists('PHPUnit_Framework_TestCase')) {
 827:             return true;
 828:             //@codingStandardsIgnoreStart
 829:         } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
 830:             //@codingStandardsIgnoreEnd
 831:             return true;
 832:         } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
 833:             return true;
 834:         }
 835: 
 836:         $prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?');
 837:         $unitTest = $this->in($prompt, array('y', 'n'), 'y');
 838:         $result = strtolower($unitTest) === 'y' || strtolower($unitTest) === 'yes';
 839: 
 840:         if ($result) {
 841:             $this->out();
 842:             $this->out(__d('cake_console', 'You can download PHPUnit from %s', 'http://phpunit.de'));
 843:         }
 844:         return $result;
 845:     }
 846: 
 847: /**
 848:  * Makes absolute file path easier to read
 849:  *
 850:  * @param string $file Absolute file path
 851:  * @return string short path
 852:  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPath
 853:  */
 854:     public function shortPath($file) {
 855:         $shortPath = str_replace(ROOT, null, $file);
 856:         $shortPath = str_replace('..' . DS, '', $shortPath);
 857:         return str_replace(DS . DS, DS, $shortPath);
 858:     }
 859: 
 860: /**
 861:  * Creates the proper controller path for the specified controller class name
 862:  *
 863:  * @param string $name Controller class name
 864:  * @return string Path to controller
 865:  */
 866:     protected function _controllerPath($name) {
 867:         return Inflector::underscore($name);
 868:     }
 869: 
 870: /**
 871:  * Creates the proper controller plural name for the specified controller class name
 872:  *
 873:  * @param string $name Controller class name
 874:  * @return string Controller plural name
 875:  */
 876:     protected function _controllerName($name) {
 877:         return Inflector::pluralize(Inflector::camelize($name));
 878:     }
 879: 
 880: /**
 881:  * Creates the proper model camelized name (singularized) for the specified name
 882:  *
 883:  * @param string $name Name
 884:  * @return string Camelized and singularized model name
 885:  */
 886:     protected function _modelName($name) {
 887:         return Inflector::camelize(Inflector::singularize($name));
 888:     }
 889: 
 890: /**
 891:  * Creates the proper underscored model key for associations
 892:  *
 893:  * @param string $name Model class name
 894:  * @return string Singular model key
 895:  */
 896:     protected function _modelKey($name) {
 897:         return Inflector::underscore($name) . '_id';
 898:     }
 899: 
 900: /**
 901:  * Creates the proper model name from a foreign key
 902:  *
 903:  * @param string $key Foreign key
 904:  * @return string Model name
 905:  */
 906:     protected function _modelNameFromKey($key) {
 907:         return Inflector::camelize(str_replace('_id', '', $key));
 908:     }
 909: 
 910: /**
 911:  * creates the singular name for use in views.
 912:  *
 913:  * @param string $name The plural underscored value.
 914:  * @return string name
 915:  */
 916:     protected function _singularName($name) {
 917:         return Inflector::variable(Inflector::singularize($name));
 918:     }
 919: 
 920: /**
 921:  * Creates the plural name for views
 922:  *
 923:  * @param string $name Name to use
 924:  * @return string Plural name for views
 925:  */
 926:     protected function _pluralName($name) {
 927:         return Inflector::variable(Inflector::pluralize($name));
 928:     }
 929: 
 930: /**
 931:  * Creates the singular human name used in views
 932:  *
 933:  * @param string $name Controller name
 934:  * @return string Singular human name
 935:  */
 936:     protected function _singularHumanName($name) {
 937:         return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
 938:     }
 939: 
 940: /**
 941:  * Creates the plural human name used in views
 942:  *
 943:  * @param string $name Controller name
 944:  * @return string Plural human name
 945:  */
 946:     protected function _pluralHumanName($name) {
 947:         return Inflector::humanize(Inflector::underscore($name));
 948:     }
 949: 
 950: /**
 951:  * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
 952:  *
 953:  * @param string $pluginName Name of the plugin you want ie. DebugKit
 954:  * @return string path path to the correct plugin.
 955:  */
 956:     protected function _pluginPath($pluginName) {
 957:         if (CakePlugin::loaded($pluginName)) {
 958:             return CakePlugin::path($pluginName);
 959:         }
 960:         return current(App::path('plugins')) . $pluginName . DS;
 961:     }
 962: 
 963: /**
 964:  * Used to enable or disable logging stream output to stdout and stderr
 965:  * If you don't wish to see in your stdout or stderr everything that is logged
 966:  * through CakeLog, call this function with first param as false
 967:  *
 968:  * @param bool $enable whether to enable CakeLog output or not
 969:  * @return void
 970:  */
 971:     protected function _useLogger($enable = true) {
 972:         if (!$enable) {
 973:             CakeLog::drop('stdout');
 974:             CakeLog::drop('stderr');
 975:             return;
 976:         }
 977:         if (!$this->_loggerIsConfigured("stdout")) {
 978:             $this->_configureStdOutLogger();
 979:         }
 980:         if (!$this->_loggerIsConfigured("stderr")) {
 981:             $this->_configureStdErrLogger();
 982:         }
 983:     }
 984: 
 985: /**
 986:  * Configure the stdout logger
 987:  * 
 988:  * @return void
 989:  */
 990:     protected function _configureStdOutLogger() {
 991:         CakeLog::config('stdout', array(
 992:             'engine' => 'Console',
 993:             'types' => array('notice', 'info'),
 994:             'stream' => $this->stdout,
 995:         ));
 996:     }
 997: 
 998: /**
 999:  * Configure the stderr logger
1000:  * 
1001:  * @return void
1002:  */
1003:     protected function _configureStdErrLogger() {
1004:         CakeLog::config('stderr', array(
1005:             'engine' => 'Console',
1006:             'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'),
1007:             'stream' => $this->stderr,
1008:         ));
1009:     }
1010: 
1011: /**
1012:  * Checks if the given logger is configured
1013:  * 
1014:  * @param string $logger The name of the logger to check 
1015:  * @return bool
1016:  */
1017:     protected function _loggerIsConfigured($logger) {
1018:         $configured = CakeLog::configured();
1019:         return in_array($logger, $configured);
1020:     }
1021: }
1022: 
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