PageRenderTime 45ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/cake/console/libs/shell.php

https://github.com/jamonardo/bank-movements
PHP | 647 lines | 286 code | 64 blank | 297 comment | 73 complexity | a5752cd9bfce4a10e72a63cd202bcaa3 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.console.libs
  17. * @since CakePHP(tm) v 1.2.0.5012
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * 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. if ($in) {
  317. return $in;
  318. }
  319. }
  320. /**
  321. * Outputs a single or multiple messages to stdout. If no parameters
  322. * are passed outputs just a newline.
  323. *
  324. * @param mixed $message A string or a an array of strings to output
  325. * @param integer $newlines Number of newlines to append
  326. * @return integer Returns the number of bytes returned from writing to stdout.
  327. * @access public
  328. */
  329. function out($message = null, $newlines = 1) {
  330. if (is_array($message)) {
  331. $message = implode($this->nl(), $message);
  332. }
  333. return $this->Dispatch->stdout($message . $this->nl($newlines), false);
  334. }
  335. /**
  336. * Outputs a single or multiple error messages to stderr. If no parameters
  337. * are passed outputs just a newline.
  338. *
  339. * @param mixed $message A string or a an array of strings to output
  340. * @param integer $newlines Number of newlines to append
  341. * @access public
  342. */
  343. function err($message = null, $newlines = 1) {
  344. if (is_array($message)) {
  345. $message = implode($this->nl(), $message);
  346. }
  347. $this->Dispatch->stderr($message . $this->nl($newlines));
  348. }
  349. /**
  350. * Returns a single or multiple linefeeds sequences.
  351. *
  352. * @param integer $multiplier Number of times the linefeed sequence should be repeated
  353. * @access public
  354. * @return string
  355. */
  356. function nl($multiplier = 1) {
  357. return str_repeat("\n", $multiplier);
  358. }
  359. /**
  360. * Outputs a series of minus characters to the standard output, acts as a visual separator.
  361. *
  362. * @param integer $newlines Number of newlines to pre- and append
  363. * @access public
  364. */
  365. function hr($newlines = 0) {
  366. $this->out(null, $newlines);
  367. $this->out('---------------------------------------------------------------');
  368. $this->out(null, $newlines);
  369. }
  370. /**
  371. * Displays a formatted error message
  372. * and exits the application with status code 1
  373. *
  374. * @param string $title Title of the error
  375. * @param string $message An optional error message
  376. * @access public
  377. */
  378. function error($title, $message = null) {
  379. $this->err(sprintf(__('Error: %s', true), $title));
  380. if (!empty($message)) {
  381. $this->err($message);
  382. }
  383. $this->_stop(1);
  384. }
  385. /**
  386. * Will check the number args matches otherwise throw an error
  387. *
  388. * @param integer $expectedNum Expected number of paramters
  389. * @param string $command Command
  390. * @access protected
  391. */
  392. function _checkArgs($expectedNum, $command = null) {
  393. if (!$command) {
  394. $command = $this->command;
  395. }
  396. if (count($this->args) < $expectedNum) {
  397. $message[] = "Got: " . count($this->args);
  398. $message[] = "Expected: {$expectedNum}";
  399. $message[] = "Please type `cake {$this->shell} help` for help";
  400. $message[] = "on usage of the {$this->name} {$command}.";
  401. $this->error('Wrong number of parameters', $message);
  402. }
  403. }
  404. /**
  405. * Creates a file at given path
  406. *
  407. * @param string $path Where to put the file.
  408. * @param string $contents Content to put in the file.
  409. * @return boolean Success
  410. * @access public
  411. */
  412. function createFile($path, $contents) {
  413. $path = str_replace(DS . DS, DS, $path);
  414. $this->out();
  415. $this->out(sprintf(__("Creating file %s", true), $path));
  416. if (is_file($path) && $this->interactive === true) {
  417. $prompt = sprintf(__('File `%s` exists, overwrite?', true), $path);
  418. $key = $this->in($prompt, array('y', 'n', 'q'), 'n');
  419. if (strtolower($key) == 'q') {
  420. $this->out(__('Quitting.', true), 2);
  421. $this->_stop();
  422. } elseif (strtolower($key) != 'y') {
  423. $this->out(sprintf(__('Skip `%s`', true), $path), 2);
  424. return false;
  425. }
  426. }
  427. if (!class_exists('File')) {
  428. require LIBS . 'file.php';
  429. }
  430. if ($File = new File($path, true)) {
  431. $data = $File->prepare($contents);
  432. $File->write($data);
  433. $this->out(sprintf(__('Wrote `%s`', true), $path));
  434. return true;
  435. } else {
  436. $this->err(sprintf(__('Could not write to `%s`.', true), $path), 2);
  437. return false;
  438. }
  439. }
  440. /**
  441. * Outputs usage text on the standard output. Implement it in subclasses.
  442. *
  443. * @access public
  444. */
  445. function help() {
  446. if ($this->command != null) {
  447. $this->err("Unknown {$this->name} command `{$this->command}`.");
  448. $this->err("For usage, try `cake {$this->shell} help`.", 2);
  449. } else {
  450. $this->Dispatch->help();
  451. }
  452. }
  453. /**
  454. * Action to create a Unit Test
  455. *
  456. * @return boolean Success
  457. * @access protected
  458. */
  459. function _checkUnitTest() {
  460. if (App::import('vendor', 'simpletest' . DS . 'simpletest')) {
  461. return true;
  462. }
  463. $prompt = 'SimpleTest is not installed. Do you want to bake unit test files anyway?';
  464. $unitTest = $this->in($prompt, array('y','n'), 'y');
  465. $result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
  466. if ($result) {
  467. $this->out();
  468. $this->out('You can download SimpleTest from http://simpletest.org');
  469. }
  470. return $result;
  471. }
  472. /**
  473. * Makes absolute file path easier to read
  474. *
  475. * @param string $file Absolute file path
  476. * @return sting short path
  477. * @access public
  478. */
  479. function shortPath($file) {
  480. $shortPath = str_replace(ROOT, null, $file);
  481. $shortPath = str_replace('..' . DS, '', $shortPath);
  482. return str_replace(DS . DS, DS, $shortPath);
  483. }
  484. /**
  485. * Creates the proper controller path for the specified controller class name
  486. *
  487. * @param string $name Controller class name
  488. * @return string Path to controller
  489. * @access protected
  490. */
  491. function _controllerPath($name) {
  492. return strtolower(Inflector::underscore($name));
  493. }
  494. /**
  495. * Creates the proper controller plural name for the specified controller class name
  496. *
  497. * @param string $name Controller class name
  498. * @return string Controller plural name
  499. * @access protected
  500. */
  501. function _controllerName($name) {
  502. return Inflector::pluralize(Inflector::camelize($name));
  503. }
  504. /**
  505. * Creates the proper controller camelized name (singularized) for the specified name
  506. *
  507. * @param string $name Name
  508. * @return string Camelized and singularized controller name
  509. * @access protected
  510. */
  511. function _modelName($name) {
  512. return Inflector::camelize(Inflector::singularize($name));
  513. }
  514. /**
  515. * Creates the proper underscored model key for associations
  516. *
  517. * @param string $name Model class name
  518. * @return string Singular model key
  519. * @access protected
  520. */
  521. function _modelKey($name) {
  522. return Inflector::underscore($name) . '_id';
  523. }
  524. /**
  525. * Creates the proper model name from a foreign key
  526. *
  527. * @param string $key Foreign key
  528. * @return string Model name
  529. * @access protected
  530. */
  531. function _modelNameFromKey($key) {
  532. return Inflector::camelize(str_replace('_id', '', $key));
  533. }
  534. /**
  535. * creates the singular name for use in views.
  536. *
  537. * @param string $name
  538. * @return string $name
  539. * @access protected
  540. */
  541. function _singularName($name) {
  542. return Inflector::variable(Inflector::singularize($name));
  543. }
  544. /**
  545. * Creates the plural name for views
  546. *
  547. * @param string $name Name to use
  548. * @return string Plural name for views
  549. * @access protected
  550. */
  551. function _pluralName($name) {
  552. return Inflector::variable(Inflector::pluralize($name));
  553. }
  554. /**
  555. * Creates the singular human name used in views
  556. *
  557. * @param string $name Controller name
  558. * @return string Singular human name
  559. * @access protected
  560. */
  561. function _singularHumanName($name) {
  562. return Inflector::humanize(Inflector::underscore(Inflector::singularize($name)));
  563. }
  564. /**
  565. * Creates the plural human name used in views
  566. *
  567. * @param string $name Controller name
  568. * @return string Plural human name
  569. * @access protected
  570. */
  571. function _pluralHumanName($name) {
  572. return Inflector::humanize(Inflector::underscore($name));
  573. }
  574. /**
  575. * Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
  576. *
  577. * @param string $pluginName Name of the plugin you want ie. DebugKit
  578. * @return string $path path to the correct plugin.
  579. */
  580. function _pluginPath($pluginName) {
  581. return App::pluginPath($pluginName);
  582. }
  583. }