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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 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

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