PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/cake/console/libs/shell.php

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