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