統計
| ブランチ: | リビジョン:

pictcode / lib / Cake / Console / Shell.php @ 0b1b8047

履歴 | 表示 | アノテート | ダウンロード (25.498 KB)

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
 * Default error code
35
 *
36
 * @var int
37
 */
38
        const CODE_ERROR = 1;
39

    
40
/**
41
 * Output constant making verbose shells.
42
 *
43
 * @var int
44
 */
45
        const VERBOSE = 2;
46

    
47
/**
48
 * Output constant for making normal shells.
49
 *
50
 * @var int
51
 */
52
        const NORMAL = 1;
53

    
54
/**
55
 * Output constants for making quiet shells.
56
 *
57
 * @var int
58
 */
59
        const QUIET = 0;
60

    
61
/**
62
 * An instance of ConsoleOptionParser that has been configured for this class.
63
 *
64
 * @var ConsoleOptionParser
65
 */
66
        public $OptionParser;
67

    
68
/**
69
 * If true, the script will ask for permission to perform actions.
70
 *
71
 * @var bool
72
 */
73
        public $interactive = true;
74

    
75
/**
76
 * Contains command switches parsed from the command line.
77
 *
78
 * @var array
79
 */
80
        public $params = array();
81

    
82
/**
83
 * The command (method/task) that is being run.
84
 *
85
 * @var string
86
 */
87
        public $command;
88

    
89
/**
90
 * Contains arguments parsed from the command line.
91
 *
92
 * @var array
93
 */
94
        public $args = array();
95

    
96
/**
97
 * The name of the shell in camelized.
98
 *
99
 * @var string
100
 */
101
        public $name = null;
102

    
103
/**
104
 * The name of the plugin the shell belongs to.
105
 * Is automatically set by ShellDispatcher when a shell is constructed.
106
 *
107
 * @var string
108
 */
109
        public $plugin = null;
110

    
111
/**
112
 * Contains tasks to load and instantiate
113
 *
114
 * @var array
115
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::$tasks
116
 */
117
        public $tasks = array();
118

    
119
/**
120
 * Contains the loaded tasks
121
 *
122
 * @var array
123
 */
124
        public $taskNames = array();
125

    
126
/**
127
 * Contains models to load and instantiate
128
 *
129
 * @var array
130
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::$uses
131
 */
132
        public $uses = array();
133

    
134
/**
135
 * This shell's primary model class name, the first model in the $uses property
136
 *
137
 * @var string
138
 */
139
        public $modelClass = null;
140

    
141
/**
142
 * Task Collection for the command, used to create Tasks.
143
 *
144
 * @var TaskCollection
145
 */
146
        public $Tasks;
147

    
148
/**
149
 * Normalized map of tasks.
150
 *
151
 * @var string
152
 */
153
        protected $_taskMap = array();
154

    
155
/**
156
 * stdout object.
157
 *
158
 * @var ConsoleOutput
159
 */
160
        public $stdout;
161

    
162
/**
163
 * stderr object.
164
 *
165
 * @var ConsoleOutput
166
 */
167
        public $stderr;
168

    
169
/**
170
 * stdin object
171
 *
172
 * @var ConsoleInput
173
 */
174
        public $stdin;
175

    
176
/**
177
 * The number of bytes last written to the output stream
178
 * used when overwriting the previous message.
179
 *
180
 * @var int
181
 */
182
        protected $_lastWritten = 0;
183

    
184
/**
185
 *  Constructs this Shell instance.
186
 *
187
 * @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
188
 * @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
189
 * @param ConsoleInput $stdin A ConsoleInput object for stdin.
190
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell
191
 */
192
        public function __construct($stdout = null, $stderr = null, $stdin = null) {
193
                if (!$this->name) {
194
                        $this->name = Inflector::camelize(str_replace(array('Shell', 'Task'), '', get_class($this)));
195
                }
196
                $this->Tasks = new TaskCollection($this);
197

    
198
                $this->stdout = $stdout ? $stdout : new ConsoleOutput('php://stdout');
199
                $this->stderr = $stderr ? $stderr : new ConsoleOutput('php://stderr');
200
                $this->stdin = $stdin ? $stdin : new ConsoleInput('php://stdin');
201

    
202
                $this->_useLogger();
203
                $parent = get_parent_class($this);
204
                if ($this->tasks !== null && $this->tasks !== false) {
205
                        $this->_mergeVars(array('tasks'), $parent, true);
206
                }
207
                if (!empty($this->uses)) {
208
                        $this->_mergeVars(array('uses'), $parent, false);
209
                }
210
        }
211

    
212
/**
213
 * Initializes the Shell
214
 * acts as constructor for subclasses
215
 * allows configuration of tasks prior to shell execution
216
 *
217
 * @return void
218
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::initialize
219
 */
220
        public function initialize() {
221
                $this->_loadModels();
222
                $this->loadTasks();
223
        }
224

    
225
/**
226
 * Starts up the Shell and displays the welcome message.
227
 * Allows for checking and configuring prior to command or main execution
228
 *
229
 * Override this method if you want to remove the welcome information,
230
 * or otherwise modify the pre-command flow.
231
 *
232
 * @return void
233
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::startup
234
 */
235
        public function startup() {
236
                $this->_welcome();
237
        }
238

    
239
/**
240
 * Displays a header for the shell
241
 *
242
 * @return void
243
 */
244
        protected function _welcome() {
245
                $this->out();
246
                $this->out(__d('cake_console', '<info>Welcome to CakePHP %s Console</info>', 'v' . Configure::version()));
247
                $this->hr();
248
                $this->out(__d('cake_console', 'App : %s', APP_DIR));
249
                $this->out(__d('cake_console', 'Path: %s', APP));
250
                $this->hr();
251
        }
252

    
253
/**
254
 * If $uses is an array load each of the models in the array
255
 *
256
 * @return bool
257
 */
258
        protected function _loadModels() {
259
                if (is_array($this->uses)) {
260
                        list(, $this->modelClass) = pluginSplit(current($this->uses));
261
                        foreach ($this->uses as $modelClass) {
262
                                $this->loadModel($modelClass);
263
                        }
264
                }
265
                return true;
266
        }
267

    
268
/**
269
 * Lazy loads models using the loadModel() method if declared in $uses
270
 *
271
 * @param string $name The name of the model to look for.
272
 * @return void
273
 */
274
        public function __isset($name) {
275
                if (is_array($this->uses)) {
276
                        foreach ($this->uses as $modelClass) {
277
                                list(, $class) = pluginSplit($modelClass);
278
                                if ($name === $class) {
279
                                        return $this->loadModel($modelClass);
280
                                }
281
                        }
282
                }
283
        }
284

    
285
/**
286
 * Loads and instantiates models required by this shell.
287
 *
288
 * @param string $modelClass Name of model class to load
289
 * @param mixed $id Initial ID the instanced model class should have
290
 * @return mixed true when single model found and instance created, error returned if model not found.
291
 * @throws MissingModelException if the model class cannot be found.
292
 */
293
        public function loadModel($modelClass = null, $id = null) {
294
                if ($modelClass === null) {
295
                        $modelClass = $this->modelClass;
296
                }
297

    
298
                $this->uses = ($this->uses) ? (array)$this->uses : array();
299
                if (!in_array($modelClass, $this->uses)) {
300
                        $this->uses[] = $modelClass;
301
                }
302

    
303
                list($plugin, $modelClass) = pluginSplit($modelClass, true);
304
                if (!isset($this->modelClass)) {
305
                        $this->modelClass = $modelClass;
306
                }
307

    
308
                $this->{$modelClass} = ClassRegistry::init(array(
309
                        'class' => $plugin . $modelClass, 'alias' => $modelClass, 'id' => $id
310
                ));
311
                if (!$this->{$modelClass}) {
312
                        throw new MissingModelException($modelClass);
313
                }
314
                return true;
315
        }
316

    
317
/**
318
 * Loads tasks defined in public $tasks
319
 *
320
 * @return bool
321
 */
322
        public function loadTasks() {
323
                if ($this->tasks === true || empty($this->tasks) || empty($this->Tasks)) {
324
                        return true;
325
                }
326
                $this->_taskMap = TaskCollection::normalizeObjectArray((array)$this->tasks);
327
                $this->taskNames = array_merge($this->taskNames, array_keys($this->_taskMap));
328
                return true;
329
        }
330

    
331
/**
332
 * Check to see if this shell has a task with the provided name.
333
 *
334
 * @param string $task The task name to check.
335
 * @return bool Success
336
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasTask
337
 */
338
        public function hasTask($task) {
339
                return isset($this->_taskMap[Inflector::camelize($task)]);
340
        }
341

    
342
/**
343
 * Check to see if this shell has a callable method by the given name.
344
 *
345
 * @param string $name The method name to check.
346
 * @return bool
347
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hasMethod
348
 */
349
        public function hasMethod($name) {
350
                try {
351
                        $method = new ReflectionMethod($this, $name);
352
                        if (!$method->isPublic() || substr($name, 0, 1) === '_') {
353
                                return false;
354
                        }
355
                        if ($method->getDeclaringClass()->name === 'Shell') {
356
                                return false;
357
                        }
358
                        return true;
359
                } catch (ReflectionException $e) {
360
                        return false;
361
                }
362
        }
363

    
364
/**
365
 * Dispatch a command to another Shell. Similar to Object::requestAction()
366
 * but intended for running shells from other shells.
367
 *
368
 * ### Usage:
369
 *
370
 * With a string command:
371
 *
372
 *        `return $this->dispatchShell('schema create DbAcl');`
373
 *
374
 * Avoid using this form if you have string arguments, with spaces in them.
375
 * The dispatched will be invoked incorrectly. Only use this form for simple
376
 * command dispatching.
377
 *
378
 * With an array command:
379
 *
380
 * `return $this->dispatchShell('schema', 'create', 'i18n', '--dry');`
381
 *
382
 * @return mixed The return of the other shell.
383
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::dispatchShell
384
 */
385
        public function dispatchShell() {
386
                $args = func_get_args();
387
                if (is_string($args[0]) && count($args) === 1) {
388
                        $args = explode(' ', $args[0]);
389
                }
390

    
391
                $Dispatcher = new ShellDispatcher($args, false);
392
                return $Dispatcher->dispatch();
393
        }
394

    
395
/**
396
 * Runs the Shell with the provided argv.
397
 *
398
 * Delegates calls to Tasks and resolves methods inside the class. Commands are looked
399
 * up with the following order:
400
 *
401
 * - Method on the shell.
402
 * - Matching task name.
403
 * - `main()` method.
404
 *
405
 * If a shell implements a `main()` method, all missing method calls will be sent to
406
 * `main()` with the original method name in the argv.
407
 *
408
 * @param string $command The command name to run on this shell. If this argument is empty,
409
 *   and the shell has a `main()` method, that will be called instead.
410
 * @param array $argv Array of arguments to run the shell with. This array should be missing the shell name.
411
 * @return void
412
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::runCommand
413
 */
414
        public function runCommand($command, $argv) {
415
                $isTask = $this->hasTask($command);
416
                $isMethod = $this->hasMethod($command);
417
                $isMain = $this->hasMethod('main');
418

    
419
                if ($isTask || $isMethod && $command !== 'execute') {
420
                        array_shift($argv);
421
                }
422

    
423
                $this->OptionParser = $this->getOptionParser();
424
                try {
425
                        list($this->params, $this->args) = $this->OptionParser->parse($argv, $command);
426
                } catch (ConsoleException $e) {
427
                        $this->out($this->OptionParser->help($command));
428
                        return false;
429
                }
430

    
431
                if (!empty($this->params['quiet'])) {
432
                        $this->_useLogger(false);
433
                }
434
                if (!empty($this->params['plugin'])) {
435
                        CakePlugin::load($this->params['plugin']);
436
                }
437
                $this->command = $command;
438
                if (!empty($this->params['help'])) {
439
                        return $this->_displayHelp($command);
440
                }
441

    
442
                if (($isTask || $isMethod || $isMain) && $command !== 'execute') {
443
                        $this->startup();
444
                }
445

    
446
                if ($isTask) {
447
                        $command = Inflector::camelize($command);
448
                        return $this->{$command}->runCommand('execute', $argv);
449
                }
450
                if ($isMethod) {
451
                        return $this->{$command}();
452
                }
453
                if ($isMain) {
454
                        return $this->main();
455
                }
456
                $this->out($this->OptionParser->help($command));
457
                return false;
458
        }
459

    
460
/**
461
 * Display the help in the correct format
462
 *
463
 * @param string $command The command to get help for.
464
 * @return void
465
 */
466
        protected function _displayHelp($command) {
467
                $format = 'text';
468
                if (!empty($this->args[0]) && $this->args[0] === 'xml') {
469
                        $format = 'xml';
470
                        $this->stdout->outputAs(ConsoleOutput::RAW);
471
                } else {
472
                        $this->_welcome();
473
                }
474
                return $this->out($this->OptionParser->help($command, $format));
475
        }
476

    
477
/**
478
 * Gets the option parser instance and configures it.
479
 *
480
 * By overriding this method you can configure the ConsoleOptionParser before returning it.
481
 *
482
 * @return ConsoleOptionParser
483
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::getOptionParser
484
 */
485
        public function getOptionParser() {
486
                $name = ($this->plugin ? $this->plugin . '.' : '') . $this->name;
487
                $parser = new ConsoleOptionParser($name);
488
                return $parser;
489
        }
490

    
491
/**
492
 * Overload get for lazy building of tasks
493
 *
494
 * @param string $name The property name to access.
495
 * @return Shell Object of Task
496
 */
497
        public function __get($name) {
498
                if (empty($this->{$name}) && in_array($name, $this->taskNames)) {
499
                        $properties = $this->_taskMap[$name];
500
                        $this->{$name} = $this->Tasks->load($properties['class'], $properties['settings']);
501
                        $this->{$name}->args =& $this->args;
502
                        $this->{$name}->params =& $this->params;
503
                        $this->{$name}->initialize();
504
                        $this->{$name}->loadTasks();
505
                }
506
                return $this->{$name};
507
        }
508

    
509
/**
510
 * Safely access the values in $this->params.
511
 *
512
 * @param string $name The name of the parameter to get.
513
 * @return string|bool|null Value. Will return null if it doesn't exist.
514
 */
515
        public function param($name) {
516
                if (!isset($this->params[$name])) {
517
                        return null;
518
                }
519
                return $this->params[$name];
520
        }
521

    
522
/**
523
 * Prompts the user for input, and returns it.
524
 *
525
 * @param string $prompt Prompt text.
526
 * @param string|array $options Array or string of options.
527
 * @param string $default Default input value.
528
 * @return mixed Either the default value, or the user-provided input.
529
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::in
530
 */
531
        public function in($prompt, $options = null, $default = null) {
532
                if (!$this->interactive) {
533
                        return $default;
534
                }
535
                $originalOptions = $options;
536
                $in = $this->_getInput($prompt, $originalOptions, $default);
537

    
538
                if ($options && is_string($options)) {
539
                        if (strpos($options, ',')) {
540
                                $options = explode(',', $options);
541
                        } elseif (strpos($options, '/')) {
542
                                $options = explode('/', $options);
543
                        } else {
544
                                $options = array($options);
545
                        }
546
                }
547
                if (is_array($options)) {
548
                        $options = array_merge(
549
                                array_map('strtolower', $options),
550
                                array_map('strtoupper', $options),
551
                                $options
552
                        );
553
                        while ($in === '' || !in_array($in, $options)) {
554
                                $in = $this->_getInput($prompt, $originalOptions, $default);
555
                        }
556
                }
557
                return $in;
558
        }
559

    
560
/**
561
 * Prompts the user for input, and returns it.
562
 *
563
 * @param string $prompt Prompt text.
564
 * @param string|array $options Array or string of options.
565
 * @param string $default Default input value.
566
 * @return Either the default value, or the user-provided input.
567
 */
568
        protected function _getInput($prompt, $options, $default) {
569
                if (!is_array($options)) {
570
                        $printOptions = '';
571
                } else {
572
                        $printOptions = '(' . implode('/', $options) . ')';
573
                }
574

    
575
                if ($default === null) {
576
                        $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . '> ', 0);
577
                } else {
578
                        $this->stdout->write('<question>' . $prompt . '</question>' . " $printOptions \n" . "[$default] > ", 0);
579
                }
580
                $result = $this->stdin->read();
581

    
582
                if ($result === false) {
583
                        $this->_stop(self::CODE_ERROR);
584
                        return self::CODE_ERROR;
585
                }
586
                $result = trim($result);
587

    
588
                if ($default !== null && ($result === '' || $result === null)) {
589
                        return $default;
590
                }
591
                return $result;
592
        }
593

    
594
/**
595
 * Wrap a block of text.
596
 * Allows you to set the width, and indenting on a block of text.
597
 *
598
 * ### Options
599
 *
600
 * - `width` The width to wrap to. Defaults to 72
601
 * - `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
602
 * - `indent` Indent the text with the string provided. Defaults to null.
603
 *
604
 * @param string $text Text the text to format.
605
 * @param string|int|array $options Array of options to use, or an integer to wrap the text to.
606
 * @return string Wrapped / indented text
607
 * @see CakeText::wrap()
608
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::wrapText
609
 */
610
        public function wrapText($text, $options = array()) {
611
                return CakeText::wrap($text, $options);
612
        }
613

    
614
/**
615
 * Outputs a single or multiple messages to stdout. If no parameters
616
 * are passed outputs just a newline.
617
 *
618
 * ### Output levels
619
 *
620
 * There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE.
621
 * The verbose and quiet output levels, map to the `verbose` and `quiet` output switches
622
 * present in most shells. Using Shell::QUIET for a message means it will always display.
623
 * While using Shell::VERBOSE means it will only display when verbose output is toggled.
624
 *
625
 * @param string|array $message A string or an array of strings to output
626
 * @param int $newlines Number of newlines to append
627
 * @param int $level The message's output level, see above.
628
 * @return int|bool Returns the number of bytes returned from writing to stdout.
629
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::out
630
 */
631
        public function out($message = null, $newlines = 1, $level = Shell::NORMAL) {
632
                $currentLevel = Shell::NORMAL;
633
                if (!empty($this->params['verbose'])) {
634
                        $currentLevel = Shell::VERBOSE;
635
                }
636
                if (!empty($this->params['quiet'])) {
637
                        $currentLevel = Shell::QUIET;
638
                }
639
                if ($level <= $currentLevel) {
640
                        $this->_lastWritten = $this->stdout->write($message, $newlines);
641
                        return $this->_lastWritten;
642
                }
643
                return true;
644
        }
645

    
646
/**
647
 * Overwrite some already output text.
648
 *
649
 * Useful for building progress bars, or when you want to replace
650
 * text already output to the screen with new text.
651
 *
652
 * **Warning** You cannot overwrite text that contains newlines.
653
 *
654
 * @param array|string $message The message to output.
655
 * @param int $newlines Number of newlines to append.
656
 * @param int $size The number of bytes to overwrite. Defaults to the
657
 *    length of the last message output.
658
 * @return int|bool Returns the number of bytes returned from writing to stdout.
659
 */
660
        public function overwrite($message, $newlines = 1, $size = null) {
661
                $size = $size ? $size : $this->_lastWritten;
662

    
663
                // Output backspaces.
664
                $this->out(str_repeat("\x08", $size), 0);
665

    
666
                $newBytes = $this->out($message, 0);
667

    
668
                // Fill any remaining bytes with spaces.
669
                $fill = $size - $newBytes;
670
                if ($fill > 0) {
671
                        $this->out(str_repeat(' ', $fill), 0);
672
                }
673
                if ($newlines) {
674
                        $this->out($this->nl($newlines), 0);
675
                }
676
        }
677

    
678
/**
679
 * Outputs a single or multiple error messages to stderr. If no parameters
680
 * are passed outputs just a newline.
681
 *
682
 * @param string|array $message A string or an array of strings to output
683
 * @param int $newlines Number of newlines to append
684
 * @return void
685
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::err
686
 */
687
        public function err($message = null, $newlines = 1) {
688
                $this->stderr->write($message, $newlines);
689
        }
690

    
691
/**
692
 * Returns a single or multiple linefeeds sequences.
693
 *
694
 * @param int $multiplier Number of times the linefeed sequence should be repeated
695
 * @return string
696
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::nl
697
 */
698
        public function nl($multiplier = 1) {
699
                return str_repeat(ConsoleOutput::LF, $multiplier);
700
        }
701

    
702
/**
703
 * Outputs a series of minus characters to the standard output, acts as a visual separator.
704
 *
705
 * @param int $newlines Number of newlines to pre- and append
706
 * @param int $width Width of the line, defaults to 63
707
 * @return void
708
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::hr
709
 */
710
        public function hr($newlines = 0, $width = 63) {
711
                $this->out(null, $newlines);
712
                $this->out(str_repeat('-', $width));
713
                $this->out(null, $newlines);
714
        }
715

    
716
/**
717
 * Displays a formatted error message
718
 * and exits the application with status code 1
719
 *
720
 * @param string $title Title of the error
721
 * @param string $message An optional error message
722
 * @return void
723
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::error
724
 */
725
        public function error($title, $message = null) {
726
                $this->err(__d('cake_console', '<error>Error:</error> %s', $title));
727

    
728
                if (!empty($message)) {
729
                        $this->err($message);
730
                }
731
                $this->_stop(self::CODE_ERROR);
732
                return self::CODE_ERROR;
733
        }
734

    
735
/**
736
 * Clear the console
737
 *
738
 * @return void
739
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::clear
740
 */
741
        public function clear() {
742
                if (empty($this->params['noclear'])) {
743
                        if (DS === '/') {
744
                                passthru('clear');
745
                        } else {
746
                                passthru('cls');
747
                        }
748
                }
749
        }
750

    
751
/**
752
 * Creates a file at given path
753
 *
754
 * @param string $path Where to put the file.
755
 * @param string $contents Content to put in the file.
756
 * @return bool Success
757
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile
758
 */
759
        public function createFile($path, $contents) {
760
                $path = str_replace(DS . DS, DS, $path);
761

    
762
                $this->out();
763

    
764
                if (is_file($path) && empty($this->params['force']) && $this->interactive === true) {
765
                        $this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
766
                        $key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
767

    
768
                        if (strtolower($key) === 'q') {
769
                                $this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
770
                                $this->_stop();
771
                                return true;
772
                        } elseif (strtolower($key) !== 'y') {
773
                                $this->out(__d('cake_console', 'Skip `%s`', $path), 2);
774
                                return false;
775
                        }
776
                } else {
777
                        $this->out(__d('cake_console', 'Creating file %s', $path));
778
                }
779

    
780
                $File = new File($path, true);
781
                if ($File->exists() && $File->writable()) {
782
                        $data = $File->prepare($contents);
783
                        $File->write($data);
784
                        $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
785
                        return true;
786
                }
787

    
788
                $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
789
                return false;
790
        }
791

    
792
/**
793
 * Action to create a Unit Test
794
 *
795
 * @return bool Success
796
 */
797
        protected function _checkUnitTest() {
798
                if (class_exists('PHPUnit_Framework_TestCase')) {
799
                        return true;
800
                        //@codingStandardsIgnoreStart
801
                } elseif (@include 'PHPUnit' . DS . 'Autoload.php') {
802
                        //@codingStandardsIgnoreEnd
803
                        return true;
804
                } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) {
805
                        return true;
806
                }
807

    
808
                $prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?');
809
                $unitTest = $this->in($prompt, array('y', 'n'), 'y');
810
                $result = strtolower($unitTest) === 'y' || strtolower($unitTest) === 'yes';
811

    
812
                if ($result) {
813
                        $this->out();
814
                        $this->out(__d('cake_console', 'You can download PHPUnit from %s', 'http://phpunit.de'));
815
                }
816
                return $result;
817
        }
818

    
819
/**
820
 * Makes absolute file path easier to read
821
 *
822
 * @param string $file Absolute file path
823
 * @return string short path
824
 * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::shortPath
825
 */
826
        public function shortPath($file) {
827
                $shortPath = str_replace(ROOT, null, $file);
828
                $shortPath = str_replace('..' . DS, '', $shortPath);
829
                return str_replace(DS . DS, DS, $shortPath);
830
        }
831

    
832
/**
833
 * Creates the proper controller path for the specified controller class name
834
 *
835
 * @param string $name Controller class name
836
 * @return string Path to controller
837
 */
838
        protected function _controllerPath($name) {
839
                return Inflector::underscore($name);
840
        }
841

    
842
/**
843
 * Creates the proper controller plural name for the specified controller class name
844
 *
845
 * @param string $name Controller class name
846
 * @return string Controller plural name
847
 */
848
        protected function _controllerName($name) {
849
                return Inflector::pluralize(Inflector::camelize($name));
850
        }
851

    
852
/**
853
 * Creates the proper model camelized name (singularized) for the specified name
854
 *
855
 * @param string $name Name
856
 * @return string Camelized and singularized model name
857
 */
858
        protected function _modelName($name) {
859
                return Inflector::camelize(Inflector::singularize($name));
860
        }
861

    
862
/**
863
 * Creates the proper underscored model key for associations
864
 *
865
 * @param string $name Model class name
866
 * @return string Singular model key
867
 */
868
        protected function _modelKey($name) {
869
                return Inflector::underscore($name) . '_id';
870
        }
871

    
872
/**
873
 * Creates the proper model name from a foreign key
874
 *
875
 * @param string $key Foreign key
876
 * @return string Model name
877
 */
878
        protected function _modelNameFromKey($key) {
879
                return Inflector::camelize(str_replace('_id', '', $key));
880
        }
881

    
882
/**
883
 * creates the singular name for use in views.
884
 *
885
 * @param string $name The plural underscored value.
886
 * @return string name
887
 */
888
        protected function _singularName($name) {
889
                return Inflector::variable(Inflector::singularize($name));
890
        }
891

    
892
/**
893
 * Creates the plural name for views
894
 *
895
 * @param string $name Name to use
896
 * @return string Plural name for views
897
 */
898
        protected function _pluralName($name) {
899
                return Inflector::variable(Inflector::pluralize($name));
900
        }
901

    
902
/**
903
 * Creates the singular human name used in views
904
 *
905
 * @param string $name Controller name
906
 * @return string Singular human name
907
 */
908
        protected function _singularHumanName($name) {
909
                return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
910
        }
911

    
912
/**
913
 * Creates the plural human name used in views
914
 *
915
 * @param string $name Controller name
916
 * @return string Plural human name
917
 */
918
        protected function _pluralHumanName($name) {
919
                return Inflector::humanize(Inflector::underscore($name));
920
        }
921

    
922
/**
923
 * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
924
 *
925
 * @param string $pluginName Name of the plugin you want ie. DebugKit
926
 * @return string path path to the correct plugin.
927
 */
928
        protected function _pluginPath($pluginName) {
929
                if (CakePlugin::loaded($pluginName)) {
930
                        return CakePlugin::path($pluginName);
931
                }
932
                return current(App::path('plugins')) . $pluginName . DS;
933
        }
934

    
935
/**
936
 * Used to enable or disable logging stream output to stdout and stderr
937
 * If you don't wish to see in your stdout or stderr everything that is logged
938
 * through CakeLog, call this function with first param as false
939
 *
940
 * @param bool $enable whether to enable CakeLog output or not
941
 * @return void
942
 */
943
        protected function _useLogger($enable = true) {
944
                if (!$enable) {
945
                        CakeLog::drop('stdout');
946
                        CakeLog::drop('stderr');
947
                        return;
948
                }
949
                CakeLog::config('stdout', array(
950
                        'engine' => 'Console',
951
                        'types' => array('notice', 'info'),
952
                        'stream' => $this->stdout,
953
                ));
954
                CakeLog::config('stderr', array(
955
                        'engine' => 'Console',
956
                        'types' => array('emergency', 'alert', 'critical', 'error', 'warning', 'debug'),
957
                        'stream' => $this->stderr,
958
                ));
959
        }
960
}