Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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