comparison cake/console/libs/shell.php @ 0:261e66bd5a0c

hg init
author Shoshi TAMAKI <shoshi@cr.ie.u-ryukyu.ac.jp>
date Sun, 24 Jul 2011 21:08:31 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:261e66bd5a0c
1 <?php
2 /**
3 * Base class for Shells
4 *
5 * PHP versions 4 and 5
6 *
7 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8 * Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
9 *
10 * Licensed under The MIT License
11 * Redistributions of files must retain the above copyright notice.
12 *
13 * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
14 * @link http://cakephp.org CakePHP(tm) Project
15 * @package cake
16 * @subpackage cake.cake.console.libs
17 * @since CakePHP(tm) v 1.2.0.5012
18 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
19 */
20
21 /**
22 * Base class for command-line utilities for automating programmer chores.
23 *
24 * @package cake
25 * @subpackage cake.cake.console.libs
26 */
27 class Shell extends Object {
28
29 /**
30 * An instance of the ShellDispatcher object that loaded this script
31 *
32 * @var ShellDispatcher
33 * @access public
34 */
35 var $Dispatch = null;
36
37 /**
38 * If true, the script will ask for permission to perform actions.
39 *
40 * @var boolean
41 * @access public
42 */
43 var $interactive = true;
44
45 /**
46 * Holds the DATABASE_CONFIG object for the app. Null if database.php could not be found,
47 * or the app does not exist.
48 *
49 * @var DATABASE_CONFIG
50 * @access public
51 */
52 var $DbConfig = null;
53
54 /**
55 * Contains command switches parsed from the command line.
56 *
57 * @var array
58 * @access public
59 */
60 var $params = array();
61
62 /**
63 * Contains arguments parsed from the command line.
64 *
65 * @var array
66 * @access public
67 */
68 var $args = array();
69
70 /**
71 * The file name of the shell that was invoked.
72 *
73 * @var string
74 * @access public
75 */
76 var $shell = null;
77
78 /**
79 * The class name of the shell that was invoked.
80 *
81 * @var string
82 * @access public
83 */
84 var $className = null;
85
86 /**
87 * The command called if public methods are available.
88 *
89 * @var string
90 * @access public
91 */
92 var $command = null;
93
94 /**
95 * The name of the shell in camelized.
96 *
97 * @var string
98 * @access public
99 */
100 var $name = null;
101
102 /**
103 * An alias for the shell
104 *
105 * @var string
106 * @access public
107 */
108 var $alias = null;
109
110 /**
111 * Contains tasks to load and instantiate
112 *
113 * @var array
114 * @access public
115 */
116 var $tasks = array();
117
118 /**
119 * Contains the loaded tasks
120 *
121 * @var array
122 * @access public
123 */
124 var $taskNames = array();
125
126 /**
127 * Contains models to load and instantiate
128 *
129 * @var array
130 * @access public
131 */
132 var $uses = array();
133
134 /**
135 * Constructs this Shell instance.
136 *
137 */
138 function __construct(&$dispatch) {
139 $vars = array('params', 'args', 'shell', 'shellCommand' => 'command');
140
141 foreach ($vars as $key => $var) {
142 if (is_string($key)) {
143 $this->{$var} =& $dispatch->{$key};
144 } else {
145 $this->{$var} =& $dispatch->{$var};
146 }
147 }
148
149 if ($this->name == null) {
150 $this->name = get_class($this);
151 }
152
153 if ($this->alias == null) {
154 $this->alias = $this->name;
155 }
156
157 ClassRegistry::addObject($this->name, $this);
158 ClassRegistry::map($this->name, $this->alias);
159
160 if (!PHP5 && isset($this->args[0])) {
161 if (strpos($this->name, strtolower(Inflector::camelize($this->args[0]))) !== false) {
162 $dispatch->shiftArgs();
163 }
164 if (strtolower($this->command) == strtolower(Inflector::variable($this->args[0])) && method_exists($this, $this->command)) {
165 $dispatch->shiftArgs();
166 }
167 }
168
169 $this->Dispatch =& $dispatch;
170 }
171
172 /**
173 * Initializes the Shell
174 * acts as constructor for subclasses
175 * allows configuration of tasks prior to shell execution
176 *
177 * @access public
178 */
179 function initialize() {
180 $this->_loadModels();
181 }
182
183 /**
184 * Starts up the Shell
185 * allows for checking and configuring prior to command or main execution
186 * can be overriden in subclasses
187 *
188 * @access public
189 */
190 function startup() {
191 $this->_welcome();
192 }
193
194 /**
195 * Displays a header for the shell
196 *
197 * @access protected
198 */
199 function _welcome() {
200 $this->Dispatch->clear();
201 $this->out();
202 $this->out('Welcome to CakePHP v' . Configure::version() . ' Console');
203 $this->hr();
204 $this->out('App : '. $this->params['app']);
205 $this->out('Path: '. $this->params['working']);
206 $this->hr();
207 }
208
209 /**
210 * Loads database file and constructs DATABASE_CONFIG class
211 * makes $this->DbConfig available to subclasses
212 *
213 * @return bool
214 * @access protected
215 */
216 function _loadDbConfig() {
217 if (config('database') && class_exists('DATABASE_CONFIG')) {
218 $this->DbConfig =& new DATABASE_CONFIG();
219 return true;
220 }
221 $this->err('Database config could not be loaded.');
222 $this->out('Run `bake` to create the database configuration.');
223 return false;
224 }
225
226 /**
227 * if var $uses = true
228 * Loads AppModel file and constructs AppModel class
229 * makes $this->AppModel available to subclasses
230 * if var $uses is an array of models will load those models
231 *
232 * @return bool
233 * @access protected
234 */
235 function _loadModels() {
236 if ($this->uses === null || $this->uses === false) {
237 return;
238 }
239
240 if ($this->uses === true && App::import('Model', 'AppModel')) {
241 $this->AppModel =& new AppModel(false, false, false);
242 return true;
243 }
244
245 if ($this->uses !== true && !empty($this->uses)) {
246 $uses = is_array($this->uses) ? $this->uses : array($this->uses);
247
248 $modelClassName = $uses[0];
249 if (strpos($uses[0], '.') !== false) {
250 list($plugin, $modelClassName) = explode('.', $uses[0]);
251 }
252 $this->modelClass = $modelClassName;
253
254 foreach ($uses as $modelClass) {
255 list($plugin, $modelClass) = pluginSplit($modelClass, true);
256 if (PHP5) {
257 $this->{$modelClass} = ClassRegistry::init($plugin . $modelClass);
258 } else {
259 $this->{$modelClass} =& ClassRegistry::init($plugin . $modelClass);
260 }
261 }
262 return true;
263 }
264 return false;
265 }
266
267 /**
268 * Loads tasks defined in var $tasks
269 *
270 * @return bool
271 * @access public
272 */
273 function loadTasks() {
274 if ($this->tasks === null || $this->tasks === false || $this->tasks === true || empty($this->tasks)) {
275 return true;
276 }
277
278 $tasks = $this->tasks;
279 if (!is_array($tasks)) {
280 $tasks = array($tasks);
281 }
282
283 foreach ($tasks as $taskName) {
284 $task = Inflector::underscore($taskName);
285 $taskClass = Inflector::camelize($taskName . 'Task');
286
287 if (!class_exists($taskClass)) {
288 foreach ($this->Dispatch->shellPaths as $path) {
289 $taskPath = $path . 'tasks' . DS . $task . '.php';
290 if (file_exists($taskPath)) {
291 require_once $taskPath;
292 break;
293 }
294 }
295 }
296 $taskClassCheck = $taskClass;
297 if (!PHP5) {
298 $taskClassCheck = strtolower($taskClass);
299 }
300 if (ClassRegistry::isKeySet($taskClassCheck)) {
301 $this->taskNames[] = $taskName;
302 if (!PHP5) {
303 $this->{$taskName} =& ClassRegistry::getObject($taskClassCheck);
304 } else {
305 $this->{$taskName} = ClassRegistry::getObject($taskClassCheck);
306 }
307 } else {
308 $this->taskNames[] = $taskName;
309 if (!PHP5) {
310 $this->{$taskName} =& new $taskClass($this->Dispatch);
311 } else {
312 $this->{$taskName} = new $taskClass($this->Dispatch);
313 }
314 }
315
316 if (!isset($this->{$taskName})) {
317 $this->err("Task `{$taskName}` could not be loaded");
318 $this->_stop();
319 }
320 }
321
322 return true;
323 }
324
325 /**
326 * Prompts the user for input, and returns it.
327 *
328 * @param string $prompt Prompt text.
329 * @param mixed $options Array or string of options.
330 * @param string $default Default input value.
331 * @return Either the default value, or the user-provided input.
332 * @access public
333 */
334 function in($prompt, $options = null, $default = null) {
335 if (!$this->interactive) {
336 return $default;
337 }
338 $in = $this->Dispatch->getInput($prompt, $options, $default);
339
340 if ($options && is_string($options)) {
341 if (strpos($options, ',')) {
342 $options = explode(',', $options);
343 } elseif (strpos($options, '/')) {
344 $options = explode('/', $options);
345 } else {
346 $options = array($options);
347 }
348 }
349 if (is_array($options)) {
350 while ($in == '' || ($in && (!in_array(strtolower($in), $options) && !in_array(strtoupper($in), $options)) && !in_array($in, $options))) {
351 $in = $this->Dispatch->getInput($prompt, $options, $default);
352 }
353 }
354 if ($in) {
355 return $in;
356 }
357 }
358
359 /**
360 * Outputs a single or multiple messages to stdout. If no parameters
361 * are passed outputs just a newline.
362 *
363 * @param mixed $message A string or a an array of strings to output
364 * @param integer $newlines Number of newlines to append
365 * @return integer Returns the number of bytes returned from writing to stdout.
366 * @access public
367 */
368 function out($message = null, $newlines = 1) {
369 if (is_array($message)) {
370 $message = implode($this->nl(), $message);
371 }
372 return $this->Dispatch->stdout($message . $this->nl($newlines), false);
373 }
374
375 /**
376 * Outputs a single or multiple error messages to stderr. If no parameters
377 * are passed outputs just a newline.
378 *
379 * @param mixed $message A string or a an array of strings to output
380 * @param integer $newlines Number of newlines to append
381 * @access public
382 */
383 function err($message = null, $newlines = 1) {
384 if (is_array($message)) {
385 $message = implode($this->nl(), $message);
386 }
387 $this->Dispatch->stderr($message . $this->nl($newlines));
388 }
389
390 /**
391 * Returns a single or multiple linefeeds sequences.
392 *
393 * @param integer $multiplier Number of times the linefeed sequence should be repeated
394 * @access public
395 * @return string
396 */
397 function nl($multiplier = 1) {
398 return str_repeat("\n", $multiplier);
399 }
400
401 /**
402 * Outputs a series of minus characters to the standard output, acts as a visual separator.
403 *
404 * @param integer $newlines Number of newlines to pre- and append
405 * @access public
406 */
407 function hr($newlines = 0) {
408 $this->out(null, $newlines);
409 $this->out('---------------------------------------------------------------');
410 $this->out(null, $newlines);
411 }
412
413 /**
414 * Displays a formatted error message
415 * and exits the application with status code 1
416 *
417 * @param string $title Title of the error
418 * @param string $message An optional error message
419 * @access public
420 */
421 function error($title, $message = null) {
422 $this->err(sprintf(__('Error: %s', true), $title));
423
424 if (!empty($message)) {
425 $this->err($message);
426 }
427 $this->_stop(1);
428 }
429
430 /**
431 * Will check the number args matches otherwise throw an error
432 *
433 * @param integer $expectedNum Expected number of paramters
434 * @param string $command Command
435 * @access protected
436 */
437 function _checkArgs($expectedNum, $command = null) {
438 if (!$command) {
439 $command = $this->command;
440 }
441 if (count($this->args) < $expectedNum) {
442 $message[] = "Got: " . count($this->args);
443 $message[] = "Expected: {$expectedNum}";
444 $message[] = "Please type `cake {$this->shell} help` for help";
445 $message[] = "on usage of the {$this->name} {$command}.";
446 $this->error('Wrong number of parameters', $message);
447 }
448 }
449
450 /**
451 * Creates a file at given path
452 *
453 * @param string $path Where to put the file.
454 * @param string $contents Content to put in the file.
455 * @return boolean Success
456 * @access public
457 */
458 function createFile($path, $contents) {
459 $path = str_replace(DS . DS, DS, $path);
460
461 $this->out();
462 $this->out(sprintf(__("Creating file %s", true), $path));
463
464 if (is_file($path) && $this->interactive === true) {
465 $prompt = sprintf(__('File `%s` exists, overwrite?', true), $path);
466 $key = $this->in($prompt, array('y', 'n', 'q'), 'n');
467
468 if (strtolower($key) == 'q') {
469 $this->out(__('Quitting.', true), 2);
470 $this->_stop();
471 } elseif (strtolower($key) != 'y') {
472 $this->out(sprintf(__('Skip `%s`', true), $path), 2);
473 return false;
474 }
475 }
476 if (!class_exists('File')) {
477 require LIBS . 'file.php';
478 }
479
480 if ($File = new File($path, true)) {
481 $data = $File->prepare($contents);
482 $File->write($data);
483 $this->out(sprintf(__('Wrote `%s`', true), $path));
484 return true;
485 } else {
486 $this->err(sprintf(__('Could not write to `%s`.', true), $path), 2);
487 return false;
488 }
489 }
490
491 /**
492 * Outputs usage text on the standard output. Implement it in subclasses.
493 *
494 * @access public
495 */
496 function help() {
497 if ($this->command != null) {
498 $this->err("Unknown {$this->name} command `{$this->command}`.");
499 $this->err("For usage, try `cake {$this->shell} help`.", 2);
500 } else {
501 $this->Dispatch->help();
502 }
503 }
504
505 /**
506 * Action to create a Unit Test
507 *
508 * @return boolean Success
509 * @access protected
510 */
511 function _checkUnitTest() {
512 if (App::import('vendor', 'simpletest' . DS . 'simpletest')) {
513 return true;
514 }
515 $prompt = 'SimpleTest is not installed. Do you want to bake unit test files anyway?';
516 $unitTest = $this->in($prompt, array('y','n'), 'y');
517 $result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
518
519 if ($result) {
520 $this->out();
521 $this->out('You can download SimpleTest from http://simpletest.org');
522 }
523 return $result;
524 }
525
526 /**
527 * Makes absolute file path easier to read
528 *
529 * @param string $file Absolute file path
530 * @return sting short path
531 * @access public
532 */
533 function shortPath($file) {
534 $shortPath = str_replace(ROOT, null, $file);
535 $shortPath = str_replace('..' . DS, '', $shortPath);
536 return str_replace(DS . DS, DS, $shortPath);
537 }
538
539 /**
540 * Creates the proper controller path for the specified controller class name
541 *
542 * @param string $name Controller class name
543 * @return string Path to controller
544 * @access protected
545 */
546 function _controllerPath($name) {
547 return strtolower(Inflector::underscore($name));
548 }
549
550 /**
551 * Creates the proper controller plural name for the specified controller class name
552 *
553 * @param string $name Controller class name
554 * @return string Controller plural name
555 * @access protected
556 */
557 function _controllerName($name) {
558 return Inflector::pluralize(Inflector::camelize($name));
559 }
560
561 /**
562 * Creates the proper controller camelized name (singularized) for the specified name
563 *
564 * @param string $name Name
565 * @return string Camelized and singularized controller name
566 * @access protected
567 */
568 function _modelName($name) {
569 return Inflector::camelize(Inflector::singularize($name));
570 }
571
572 /**
573 * Creates the proper underscored model key for associations
574 *
575 * @param string $name Model class name
576 * @return string Singular model key
577 * @access protected
578 */
579 function _modelKey($name) {
580 return Inflector::underscore($name) . '_id';
581 }
582
583 /**
584 * Creates the proper model name from a foreign key
585 *
586 * @param string $key Foreign key
587 * @return string Model name
588 * @access protected
589 */
590 function _modelNameFromKey($key) {
591 return Inflector::camelize(str_replace('_id', '', $key));
592 }
593
594 /**
595 * creates the singular name for use in views.
596 *
597 * @param string $name
598 * @return string $name
599 * @access protected
600 */
601 function _singularName($name) {
602 return Inflector::variable(Inflector::singularize($name));
603 }
604
605 /**
606 * Creates the plural name for views
607 *
608 * @param string $name Name to use
609 * @return string Plural name for views
610 * @access protected
611 */
612 function _pluralName($name) {
613 return Inflector::variable(Inflector::pluralize($name));
614 }
615
616 /**
617 * Creates the singular human name used in views
618 *
619 * @param string $name Controller name
620 * @return string Singular human name
621 * @access protected
622 */
623 function _singularHumanName($name) {
624 return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
625 }
626
627 /**
628 * Creates the plural human name used in views
629 *
630 * @param string $name Controller name
631 * @return string Plural human name
632 * @access protected
633 */
634 function _pluralHumanName($name) {
635 return Inflector::humanize(Inflector::underscore($name));
636 }
637
638 /**
639 * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
640 *
641 * @param string $pluginName Name of the plugin you want ie. DebugKit
642 * @return string $path path to the correct plugin.
643 */
644 function _pluginPath($pluginName) {
645 return App::pluginPath($pluginName);
646 }
647 }