1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 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: 29: 30: 31:
32: class Shell extends Object {
33:
34: 35: 36: 37: 38:
39: const VERBOSE = 2;
40:
41: 42: 43: 44: 45:
46: const NORMAL = 1;
47:
48: 49: 50: 51: 52:
53: const QUIET = 0;
54:
55: 56: 57: 58: 59:
60: public $OptionParser;
61:
62: 63: 64: 65: 66:
67: public $interactive = true;
68:
69: 70: 71: 72: 73:
74: public $params = array();
75:
76: 77: 78: 79: 80:
81: public $command;
82:
83: 84: 85: 86: 87:
88: public $args = array();
89:
90: 91: 92: 93: 94:
95: public $name = null;
96:
97: 98: 99: 100: 101: 102:
103: public $plugin = null;
104:
105: 106: 107: 108: 109: 110:
111: public $tasks = array();
112:
113: 114: 115: 116: 117:
118: public $taskNames = array();
119:
120: 121: 122: 123: 124: 125:
126: public $uses = array();
127:
128: 129: 130: 131: 132:
133: public $modelClass = null;
134:
135: 136: 137: 138: 139:
140: public $Tasks;
141:
142: 143: 144: 145: 146:
147: protected $_taskMap = array();
148:
149: 150: 151: 152: 153:
154: public $stdout;
155:
156: 157: 158: 159: 160:
161: public $stderr;
162:
163: 164: 165: 166: 167:
168: public $stdin;
169:
170: 171: 172: 173: 174: 175: 176: 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: 200: 201: 202: 203: 204: 205:
206: public function initialize() {
207: $this->_loadModels();
208: $this->loadTasks();
209: }
210:
211: 212: 213: 214: 215: 216: 217: 218: 219: 220:
221: public function startup() {
222: $this->_welcome();
223: }
224:
225: 226: 227: 228: 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: 241: 242: 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: 256: 257: 258: 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: 273: 274: 275: 276: 277: 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: 305: 306: 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: 319: 320: 321: 322: 323:
324: public function hasTask($task) {
325: return isset($this->_taskMap[Inflector::camelize($task)]);
326: }
327:
328: 329: 330: 331: 332: 333: 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: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 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: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 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: 448: 449: 450: 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: 465: 466: 467: 468: 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: 478: 479: 480: 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: 496: 497: 498: 499: 500: 501: 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: 534: 535: 536: 537: 538: 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: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580:
581: public function wrapText($text, $options = array()) {
582: return String::wrap($text, $options);
583: }
584:
585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 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: 618: 619: 620: 621: 622: 623: 624:
625: public function err($message = null, $newlines = 1) {
626: $this->stderr->write($message, $newlines);
627: }
628:
629: 630: 631: 632: 633: 634: 635:
636: public function nl($multiplier = 1) {
637: return str_repeat(ConsoleOutput::LF, $multiplier);
638: }
639:
640: 641: 642: 643: 644: 645: 646: 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: 656: 657: 658: 659: 660: 661: 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: 674: 675: 676: 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: 690: 691: 692: 693: 694: 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: 730: 731: 732:
733: protected function _checkUnitTest() {
734: if (class_exists('PHPUnit_Framework_TestCase')) {
735: return true;
736:
737: } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
738:
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: 757: 758: 759: 760: 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: 770: 771: 772: 773:
774: protected function _controllerPath($name) {
775: return Inflector::underscore($name);
776: }
777:
778: 779: 780: 781: 782: 783:
784: protected function _controllerName($name) {
785: return Inflector::pluralize(Inflector::camelize($name));
786: }
787:
788: 789: 790: 791: 792: 793:
794: protected function _modelName($name) {
795: return Inflector::camelize(Inflector::singularize($name));
796: }
797:
798: 799: 800: 801: 802: 803:
804: protected function _modelKey($name) {
805: return Inflector::underscore($name) . '_id';
806: }
807:
808: 809: 810: 811: 812: 813:
814: protected function _modelNameFromKey($key) {
815: return Inflector::camelize(str_replace('_id', '', $key));
816: }
817:
818: 819: 820: 821: 822: 823:
824: protected function _singularName($name) {
825: return Inflector::variable(Inflector::singularize($name));
826: }
827:
828: 829: 830: 831: 832: 833:
834: protected function _pluralName($name) {
835: return Inflector::variable(Inflector::pluralize($name));
836: }
837:
838: 839: 840: 841: 842: 843:
844: protected function _singularHumanName($name) {
845: return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
846: }
847:
848: 849: 850: 851: 852: 853:
854: protected function _pluralHumanName($name) {
855: return Inflector::humanize(Inflector::underscore($name));
856: }
857:
858: 859: 860: 861: 862: 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: 873: 874: 875: 876: 877: 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: