ConsoleShell.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 1.2.0.5012
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. App::uses('AppShell', 'Console/Command');
  16. /**
  17. * Provides a very basic 'interactive' console for CakePHP apps.
  18. *
  19. * @package Cake.Console.Command
  20. * @deprecated Deprecated since version 2.4, will be removed in 3.0
  21. */
  22. class ConsoleShell extends AppShell {
  23. /**
  24. * Available binding types
  25. *
  26. * @var array
  27. */
  28. public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
  29. /**
  30. * Chars that describe invalid commands
  31. *
  32. * @var array
  33. */
  34. public $badCommandChars = array('$', ';');
  35. /**
  36. * Available models
  37. *
  38. * @var array
  39. */
  40. public $models = array();
  41. /**
  42. * _finished
  43. *
  44. * This shell is perpetual, setting this property to true exits the process
  45. *
  46. * @var mixed
  47. */
  48. protected $_finished = false;
  49. /**
  50. * _methodPatterns
  51. *
  52. * @var array
  53. */
  54. protected $_methodPatterns = array(
  55. 'help' => '/^(help|\?)/',
  56. '_exit' => '/^(quit|exit)/',
  57. '_models' => '/^models/i',
  58. '_bind' => '/^(\w+) bind (\w+) (\w+)/',
  59. '_unbind' => '/^(\w+) unbind (\w+) (\w+)/',
  60. '_find' => '/.+->find/',
  61. '_save' => '/.+->save/',
  62. '_columns' => '/^(\w+) columns/',
  63. '_routesReload' => '/^routes\s+reload/i',
  64. '_routesShow' => '/^routes\s+show/i',
  65. '_routeToString' => '/^route\s+(\(.*\))$/i',
  66. '_routeToArray' => '/^route\s+(.*)$/i',
  67. );
  68. /**
  69. * Override startup of the Shell
  70. *
  71. * @return void
  72. */
  73. public function startup() {
  74. App::uses('Dispatcher', 'Routing');
  75. $this->Dispatcher = new Dispatcher();
  76. $this->models = App::objects('Model');
  77. foreach ($this->models as $model) {
  78. $class = $model;
  79. App::uses($class, 'Model');
  80. $this->{$class} = new $class();
  81. }
  82. $this->out(__d('cake_console', 'Model classes:'));
  83. $this->hr();
  84. foreach ($this->models as $model) {
  85. $this->out(" - {$model}");
  86. }
  87. if (!$this->_loadRoutes()) {
  88. $message = __d(
  89. 'cake_console',
  90. 'There was an error loading the routes config. Please check that the file exists and contains no errors.'
  91. );
  92. $this->err($message);
  93. }
  94. }
  95. /**
  96. * Gets the option parser instance and configures it.
  97. *
  98. * @return ConsoleOptionParser
  99. */
  100. public function getOptionParser() {
  101. $parser = parent::getOptionParser();
  102. $parser->description(array(
  103. 'The interactive console is a tool for testing parts of your',
  104. 'app before you write code.',
  105. '',
  106. 'See below for a list of supported commands.'
  107. ))->epilog(array(
  108. '<info>Model testing</info>',
  109. '',
  110. 'To test model results, use the name of your model without a leading $',
  111. 'e.g. Foo->find("all")',
  112. "",
  113. 'To dynamically set associations, you can do the following:',
  114. '',
  115. "\tModelA bind <association> ModelB",
  116. '',
  117. "where the supported associations are hasOne, hasMany, belongsTo, hasAndBelongsToMany",
  118. "",
  119. 'To dynamically remove associations, you can do the following:',
  120. '',
  121. "\t ModelA unbind <association> ModelB",
  122. '',
  123. "where the supported associations are the same as above",
  124. "",
  125. "To save a new field in a model, you can do the following:",
  126. '',
  127. "\tModelA->save(array('foo' => 'bar', 'baz' => 0))",
  128. '',
  129. "where you are passing a hash of data to be saved in the format",
  130. "of field => value pairs",
  131. "",
  132. "To get column information for a model, use the following:",
  133. '',
  134. "\tModelA columns",
  135. '',
  136. "which returns a list of columns and their type",
  137. "",
  138. '<info>Route testing</info>',
  139. "",
  140. 'To test URLs against your app\'s route configuration, type:',
  141. "",
  142. "\tRoute <url>",
  143. "",
  144. "where url is the path to your your action plus any query parameters,",
  145. "minus the application's base path. For example:",
  146. "",
  147. "\tRoute /posts/view/1",
  148. "",
  149. "will return something like the following:",
  150. "",
  151. "\tarray(",
  152. "\t [...]",
  153. "\t 'controller' => 'posts',",
  154. "\t 'action' => 'view',",
  155. "\t [...]",
  156. "\t)",
  157. "",
  158. 'Alternatively, you can use simple array syntax to test reverse',
  159. 'To reload your routes config (Config/routes.php), do the following:',
  160. "",
  161. "\tRoutes reload",
  162. "",
  163. 'To show all connected routes, do the following:',
  164. '',
  165. "\tRoutes show",
  166. ));
  167. return $parser;
  168. }
  169. /**
  170. * Prints the help message
  171. *
  172. * @return void
  173. */
  174. public function help() {
  175. $optionParser = $this->getOptionParser();
  176. $this->out($optionParser->epilog());
  177. }
  178. /**
  179. * Override main() to handle action
  180. *
  181. * @param string $command The command to run.
  182. * @return void
  183. */
  184. public function main($command = null) {
  185. $this->_finished = false;
  186. while (!$this->_finished) {
  187. if (empty($command)) {
  188. $command = trim($this->in(''));
  189. }
  190. $method = $this->_method($command);
  191. if ($method) {
  192. $this->$method($command);
  193. } else {
  194. $this->out(__d('cake_console', "Invalid command"));
  195. $this->out();
  196. }
  197. $command = '';
  198. }
  199. }
  200. /**
  201. * Determine the method to process the current command
  202. *
  203. * @param string $command The command to run.
  204. * @return string or false
  205. */
  206. protected function _method($command) {
  207. foreach ($this->_methodPatterns as $method => $pattern) {
  208. if (preg_match($pattern, $command)) {
  209. return $method;
  210. }
  211. }
  212. return false;
  213. }
  214. /**
  215. * Set the finiished property so that the loop in main method ends
  216. *
  217. * @return void
  218. */
  219. protected function _exit() {
  220. $this->_finished = true;
  221. }
  222. /**
  223. * List all models
  224. *
  225. * @return void
  226. */
  227. protected function _models() {
  228. $this->out(__d('cake_console', 'Model classes:'));
  229. $this->hr();
  230. foreach ($this->models as $model) {
  231. $this->out(" - {$model}");
  232. }
  233. }
  234. /**
  235. * Bind an association
  236. *
  237. * @param mixed $command The command to run.
  238. * @return void
  239. */
  240. protected function _bind($command) {
  241. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  242. foreach ($tmp as $data) {
  243. $data = strip_tags($data);
  244. $data = str_replace($this->badCommandChars, "", $data);
  245. }
  246. $modelA = $tmp[1];
  247. $association = $tmp[2];
  248. $modelB = $tmp[3];
  249. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
  250. $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
  251. $this->out(__d('cake_console', "Created %s association between %s and %s",
  252. $association, $modelA, $modelB));
  253. } else {
  254. $this->out(__d('cake_console', "Please verify you are using valid models and association types"));
  255. }
  256. }
  257. /**
  258. * Unbind an association
  259. *
  260. * @param mixed $command The command to run.
  261. * @return void
  262. */
  263. protected function _unbind($command) {
  264. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  265. foreach ($tmp as $data) {
  266. $data = strip_tags($data);
  267. $data = str_replace($this->badCommandChars, "", $data);
  268. }
  269. $modelA = $tmp[1];
  270. $association = $tmp[2];
  271. $modelB = $tmp[3];
  272. // Verify that there is actually an association to unbind
  273. $currentAssociations = $this->{$modelA}->getAssociated();
  274. $validCurrentAssociation = false;
  275. foreach ($currentAssociations as $model => $currentAssociation) {
  276. if ($model === $modelB && $association === $currentAssociation) {
  277. $validCurrentAssociation = true;
  278. }
  279. }
  280. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
  281. $this->{$modelA}->unbindModel(array($association => array($modelB)));
  282. $this->out(__d('cake_console', "Removed %s association between %s and %s",
  283. $association, $modelA, $modelB));
  284. } else {
  285. $this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
  286. }
  287. }
  288. /**
  289. * Perform a find
  290. *
  291. * @param mixed $command The command to run.
  292. * @return void
  293. */
  294. protected function _find($command) {
  295. $command = strip_tags($command);
  296. $command = str_replace($this->badCommandChars, "", $command);
  297. // Do we have a valid model?
  298. list($modelToCheck) = explode('->', $command);
  299. if ($this->_isValidModel($modelToCheck)) {
  300. $findCommand = "\$data = \$this->$command;";
  301. //@codingStandardsIgnoreStart
  302. @eval($findCommand);
  303. //@codingStandardsIgnoreEnd
  304. if (is_array($data)) {
  305. foreach ($data as $idx => $results) {
  306. if (is_numeric($idx)) { // findAll() output
  307. foreach ($results as $modelName => $result) {
  308. $this->out("$modelName");
  309. foreach ($result as $field => $value) {
  310. if (is_array($value)) {
  311. foreach ($value as $field2 => $value2) {
  312. $this->out("\t$field2: $value2");
  313. }
  314. $this->out();
  315. } else {
  316. $this->out("\t$field: $value");
  317. }
  318. }
  319. }
  320. } else { // find() output
  321. $this->out($idx);
  322. foreach ($results as $field => $value) {
  323. if (is_array($value)) {
  324. foreach ($value as $field2 => $value2) {
  325. $this->out("\t$field2: $value2");
  326. }
  327. $this->out();
  328. } else {
  329. $this->out("\t$field: $value");
  330. }
  331. }
  332. }
  333. }
  334. } else {
  335. $this->out();
  336. $this->out(__d('cake_console', "No result set found"));
  337. }
  338. } else {
  339. $this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
  340. }
  341. }
  342. /**
  343. * Save a record
  344. *
  345. * @param mixed $command The command to run.
  346. * @return void
  347. */
  348. protected function _save($command) {
  349. // Validate the model we're trying to save here
  350. $command = strip_tags($command);
  351. $command = str_replace($this->badCommandChars, "", $command);
  352. list($modelToSave) = explode("->", $command);
  353. if ($this->_isValidModel($modelToSave)) {
  354. // Extract the array of data we are trying to build
  355. list(, $data) = explode("->save", $command);
  356. $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
  357. $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
  358. //@codingStandardsIgnoreStart
  359. @eval($saveCommand);
  360. //@codingStandardsIgnoreEnd
  361. $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
  362. }
  363. }
  364. /**
  365. * Show the columns for a model
  366. *
  367. * @param mixed $command The command to run.
  368. * @return void
  369. */
  370. protected function _columns($command) {
  371. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  372. $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
  373. if ($this->_isValidModel($modelToCheck)) {
  374. // Get the column info for this model
  375. $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
  376. //@codingStandardsIgnoreStart
  377. @eval($fieldsCommand);
  378. //@codingStandardsIgnoreEnd
  379. if (is_array($data)) {
  380. foreach ($data as $field => $type) {
  381. $this->out("\t{$field}: {$type}");
  382. }
  383. }
  384. } else {
  385. $this->out(__d('cake_console', "Please verify that you selected a valid model"));
  386. }
  387. }
  388. /**
  389. * Reload route definitions
  390. *
  391. * @return void
  392. */
  393. protected function _routesReload() {
  394. if (!$this->_loadRoutes()) {
  395. return $this->err(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
  396. }
  397. $this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count(Router::$routes)));
  398. }
  399. /**
  400. * Show all routes
  401. *
  402. * @return void
  403. */
  404. protected function _routesShow() {
  405. $this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults'), true));
  406. }
  407. /**
  408. * Parse an array URL and show the equivalent URL as a string
  409. *
  410. * @param mixed $command The command to run.
  411. * @return void
  412. */
  413. protected function _routeToString($command) {
  414. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  415. //@codingStandardsIgnoreStart
  416. if ($url = eval('return array' . $tmp[1] . ';')) {
  417. //@codingStandardsIgnoreEnd
  418. $this->out(Router::url($url));
  419. }
  420. }
  421. /**
  422. * Parse a string URL and show as an array
  423. *
  424. * @param mixed $command The command to run.
  425. * @return void
  426. */
  427. protected function _routeToArray($command) {
  428. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  429. $this->out(var_export(Router::parse($tmp[1]), true));
  430. }
  431. /**
  432. * Tells if the specified model is included in the list of available models
  433. *
  434. * @param string $modelToCheck The model to check.
  435. * @return boolean true if is an available model, false otherwise
  436. */
  437. protected function _isValidModel($modelToCheck) {
  438. return in_array($modelToCheck, $this->models);
  439. }
  440. /**
  441. * Reloads the routes configuration from app/Config/routes.php, and compiles
  442. * all routes found
  443. *
  444. * @return boolean True if config reload was a success, otherwise false
  445. */
  446. protected function _loadRoutes() {
  447. Router::reload();
  448. extract(Router::getNamedExpressions());
  449. //@codingStandardsIgnoreStart
  450. if (!@include APP . 'Config' . DS . 'routes.php') {
  451. //@codingStandardsIgnoreEnd
  452. return false;
  453. }
  454. CakePlugin::routes();
  455. Router::parse('/');
  456. return true;
  457. }
  458. }