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 int
38: */
39: const VERBOSE = 2;
40:
41: /**
42: * Output constant for making normal shells.
43: *
44: * @var int
45: */
46: const NORMAL = 1;
47:
48: /**
49: * Output constants for making quiet shells.
50: *
51: * @var int
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 bool
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 bool
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 The name of the model to look for.
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 bool
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 bool 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 bool
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 The command to get help for.
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: *
466: * By overriding this method you can configure the ConsoleOptionParser before returning it.
467: *
468: * @return ConsoleOptionParser
469: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::getOptionParser
470: */
471: public function getOptionParser() {
472: $name = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
473: $parser = new ConsoleOptionParser($name);
474: return $parser;
475: }
476:
477: /**
478: * Overload get for lazy building of tasks
479: *
480: * @param string $name The property name to access.
481: * @return Shell Object of Task
482: */
483: public function __get($name) {
484: if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
485: $properties = $this->_taskMap[$name];
486: $this->{$name} = $this->Tasks->load($properties['class'], $properties['settings']);
487: $this->{$name}->args =& $this->args;
488: $this->{$name}->params =& $this->params;
489: $this->{$name}->initialize();
490: $this->{$name}->loadTasks();
491: }
492: return $this->{$name};
493: }
494:
495: /**
496: * Prompts the user for input, and returns it.
497: *
498: * @param string $prompt Prompt text.
499: * @param string|array $options Array or string of options.
500: * @param string $default Default input value.
501: * @return mixed Either the default value, or the user-provided input.
502: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::in
503: */
504: public function in($prompt, $options = null, $default = null) {
505: if (!$this->interactive) {
506: return $default;
507: }
508: $originalOptions = $options;
509: $in = $this->_getInput($prompt, $originalOptions, $default);
510:
511: if ($options && is_string($options)) {
512: if (strpos($options, ',')) {
513: $options = explode(',', $options);
514: } elseif (strpos($options, '/')) {
515: $options = explode('/', $options);
516: } else {
517: $options = array($options);
518: }
519: }
520: if (is_array($options)) {
521: $options = array_merge(
522: array_map('strtolower', $options),
523: array_map('strtoupper', $options),
524: $options
525: );
526: while ($in === '' || !in_array($in, $options)) {
527: $in = $this->_getInput($prompt, $originalOptions, $default);
528: }
529: }
530: return $in;
531: }
532:
533: /**
534: * Prompts the user for input, and returns it.
535: *
536: * @param string $prompt Prompt text.
537: * @param string|array $options Array or string of options.
538: * @param string $default Default input value.
539: * @return Either the default value, or the user-provided input.
540: */
541: protected function _getInput($prompt, $options, $default) {
542: if (!is_array($options)) {
543: $printOptions = '';
544: } else {
545: $printOptions = '(' . implode('/', $options) . ')';
546: }
547:
548: if ($default === null) {
549: $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . '> ', 0);
550: } else {
551: $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . "[$default] > ", 0);
552: }
553: $result = $this->stdin->read();
554:
555: if ($result === false) {
556: return $this->_stop(1);
557: }
558: $result = trim($result);
559:
560: if ($default !== null && ($result === '' || $result === null)) {
561: return $default;
562: }
563: return $result;
564: }
565:
566: /**
567: * Wrap a block of text.
568: * Allows you to set the width, and indenting on a block of text.
569: *
570: * ### Options
571: *
572: * - `width` The width to wrap to. Defaults to 72
573: * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
574: * - `indent` Indent the text with the string provided. Defaults to null.
575: *
576: * @param string $text Text the text to format.
577: * @param string|int|array $options Array of options to use, or an integer to wrap the text to.
578: * @return string Wrapped / indented text
579: * @see String::wrap()
580: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapText
581: */
582: public function wrapText($text, $options = array()) {
583: return String::wrap($text, $options);
584: }
585:
586: /**
587: * Outputs a single or multiple messages to stdout. If no parameters
588: * are passed outputs just a newline.
589: *
590: * ### Output levels
591: *
592: * There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE.
593: * The verbose and quiet output levels, map to the `verbose` and `quiet` output switches
594: * present in most shells. Using Shell::QUIET for a message means it will always display.
595: * While using Shell::VERBOSE means it will only display when verbose output is toggled.
596: *
597: * @param string|array $message A string or an array of strings to output
598: * @param int $newlines Number of newlines to append
599: * @param int $level The message's output level, see above.
600: * @return int|bool Returns the number of bytes returned from writing to stdout.
601: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::out
602: */
603: public function out($message = null, $newlines = 1, $level = Shell::NORMAL) {
604: $currentLevel = Shell::NORMAL;
605: if (!empty($this->params['verbose'])) {
606: $currentLevel = Shell::VERBOSE;
607: }
608: if (!empty($this->params['quiet'])) {
609: $currentLevel = Shell::QUIET;
610: }
611: if ($level <= $currentLevel) {
612: return $this->stdout->write($message, $newlines);
613: }
614: return true;
615: }
616:
617: /**
618: * Outputs a single or multiple error messages to stderr. If no parameters
619: * are passed outputs just a newline.
620: *
621: * @param string|array $message A string or an array of strings to output
622: * @param int $newlines Number of newlines to append
623: * @return void
624: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::err
625: */
626: public function err($message = null, $newlines = 1) {
627: $this->stderr->write($message, $newlines);
628: }
629:
630: /**
631: * Returns a single or multiple linefeeds sequences.
632: *
633: * @param int $multiplier Number of times the linefeed sequence should be repeated
634: * @return string
635: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nl
636: */
637: public function nl($multiplier = 1) {
638: return str_repeat(ConsoleOutput::LF, $multiplier);
639: }
640:
641: /**
642: * Outputs a series of minus characters to the standard output, acts as a visual separator.
643: *
644: * @param int $newlines Number of newlines to pre- and append
645: * @param int $width Width of the line, defaults to 63
646: * @return void
647: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hr
648: */
649: public function hr($newlines = 0, $width = 63) {
650: $this->out(null, $newlines);
651: $this->out(str_repeat('-', $width));
652: $this->out(null, $newlines);
653: }
654:
655: /**
656: * Displays a formatted error message
657: * and exits the application with status code 1
658: *
659: * @param string $title Title of the error
660: * @param string $message An optional error message
661: * @return void
662: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::error
663: */
664: public function error($title, $message = null) {
665: $this->err(__d('cake_console', '<error>Error:</error> %s', $title));
666:
667: if (!empty($message)) {
668: $this->err($message);
669: }
670: return $this->_stop(1);
671: }
672:
673: /**
674: * Clear the console
675: *
676: * @return void
677: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clear
678: */
679: public function clear() {
680: if (empty($this->params['noclear'])) {
681: if (DS === '/') {
682: passthru('clear');
683: } else {
684: passthru('cls');
685: }
686: }
687: }
688:
689: /**
690: * Creates a file at given path
691: *
692: * @param string $path Where to put the file.
693: * @param string $contents Content to put in the file.
694: * @return bool Success
695: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile
696: */
697: public function createFile($path, $contents) {
698: $path = str_replace(DS . DS, DS, $path);
699:
700: $this->out();
701:
702: if (is_file($path) && empty($this->params['force']) && $this->interactive === true) {
703: $this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
704: $key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
705:
706: if (strtolower($key) === 'q') {
707: $this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
708: return $this->_stop();
709: } elseif (strtolower($key) !== 'y') {
710: $this->out(__d('cake_console', 'Skip `%s`', $path), 2);
711: return false;
712: }
713: } else {
714: $this->out(__d('cake_console', 'Creating file %s', $path));
715: }
716:
717: $File = new File($path, true);
718: if ($File->exists() && $File->writable()) {
719: $data = $File->prepare($contents);
720: $File->write($data);
721: $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
722: return true;
723: }
724:
725: $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
726: return false;
727: }
728:
729: /**
730: * Action to create a Unit Test
731: *
732: * @return bool Success
733: */
734: protected function _checkUnitTest() {
735: if (class_exists('PHPUnit_Framework_TestCase')) {
736: return true;
737: //@codingStandardsIgnoreStart
738: } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
739: //@codingStandardsIgnoreEnd
740: return true;
741: } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
742: return true;
743: }
744:
745: $prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?');
746: $unitTest = $this->in($prompt, array('y', 'n'), 'y');
747: $result = strtolower($unitTest) === 'y' || strtolower($unitTest) === 'yes';
748:
749: if ($result) {
750: $this->out();
751: $this->out(__d('cake_console', 'You can download PHPUnit from %s', 'http://phpunit.de'));
752: }
753: return $result;
754: }
755:
756: /**
757: * Makes absolute file path easier to read
758: *
759: * @param string $file Absolute file path
760: * @return string short path
761: * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPath
762: */
763: public function shortPath($file) {
764: $shortPath = str_replace(ROOT, null, $file);
765: $shortPath = str_replace('..' . DS, '', $shortPath);
766: return str_replace(DS . DS, DS, $shortPath);
767: }
768:
769: /**
770: * Creates the proper controller path for the specified controller class name
771: *
772: * @param string $name Controller class name
773: * @return string Path to controller
774: */
775: protected function _controllerPath($name) {
776: return Inflector::underscore($name);
777: }
778:
779: /**
780: * Creates the proper controller plural name for the specified controller class name
781: *
782: * @param string $name Controller class name
783: * @return string Controller plural name
784: */
785: protected function _controllerName($name) {
786: return Inflector::pluralize(Inflector::camelize($name));
787: }
788:
789: /**
790: * Creates the proper model camelized name (singularized) for the specified name
791: *
792: * @param string $name Name
793: * @return string Camelized and singularized model name
794: */
795: protected function _modelName($name) {
796: return Inflector::camelize(Inflector::singularize($name));
797: }
798:
799: /**
800: * Creates the proper underscored model key for associations
801: *
802: * @param string $name Model class name
803: * @return string Singular model key
804: */
805: protected function _modelKey($name) {
806: return Inflector::underscore($name) . '_id';
807: }
808:
809: /**
810: * Creates the proper model name from a foreign key
811: *
812: * @param string $key Foreign key
813: * @return string Model name
814: */
815: protected function _modelNameFromKey($key) {
816: return Inflector::camelize(str_replace('_id', '', $key));
817: }
818:
819: /**
820: * creates the singular name for use in views.
821: *
822: * @param string $name The plural underscored value.
823: * @return string name
824: */
825: protected function _singularName($name) {
826: return Inflector::variable(Inflector::singularize($name));
827: }
828:
829: /**
830: * Creates the plural name for views
831: *
832: * @param string $name Name to use
833: * @return string Plural name for views
834: */
835: protected function _pluralName($name) {
836: return Inflector::variable(Inflector::pluralize($name));
837: }
838:
839: /**
840: * Creates the singular human name used in views
841: *
842: * @param string $name Controller name
843: * @return string Singular human name
844: */
845: protected function _singularHumanName($name) {
846: return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
847: }
848:
849: /**
850: * Creates the plural human name used in views
851: *
852: * @param string $name Controller name
853: * @return string Plural human name
854: */
855: protected function _pluralHumanName($name) {
856: return Inflector::humanize(Inflector::underscore($name));
857: }
858:
859: /**
860: * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
861: *
862: * @param string $pluginName Name of the plugin you want ie. DebugKit
863: * @return string path path to the correct plugin.
864: */
865: protected function _pluginPath($pluginName) {
866: if (CakePlugin::loaded($pluginName)) {
867: return CakePlugin::path($pluginName);
868: }
869: return current(App::path('plugins')) . $pluginName . DS;
870: }
871:
872: /**
873: * Used to enable or disable logging stream output to stdout and stderr
874: * If you don't wish to see in your stdout or stderr everything that is logged
875: * through CakeLog, call this function with first param as false
876: *
877: * @param bool $enable whether to enable CakeLog output or not
878: * @return void
879: */
880: protected function _useLogger($enable = true) {
881: if (!$enable) {
882: CakeLog::drop('stdout');
883: CakeLog::drop('stderr');
884: return;
885: }
886: CakeLog::config('stdout', array(
887: 'engine' => 'Console',
888: 'types' => array('notice', 'info'),
889: 'stream' => $this->stdout,
890: ));
891: CakeLog::config('stderr', array(
892: 'engine' => 'Console',
893: 'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'),
894: 'stream' => $this->stderr,
895: ));
896: }
897: }
898: