Subversion-Projekte lars-tiefland.cakephp

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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