ConsoleShell.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. * getOptionParser
  97. *
  98. * @return void
  99. */
  100. public function getOptionParser() {
  101. $description = array(
  102. 'The interactive console is a tool for testing parts of your',
  103. 'app before you write code.',
  104. '',
  105. 'See below for a list of supported commands.'
  106. );
  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 parent::getOptionParser()
  168. ->description($description)
  169. ->epilog($epilog);
  170. }
  171. /**
  172. * Prints the help message
  173. *
  174. * @return void
  175. */
  176. public function help() {
  177. $optionParser = $this->getOptionParser();
  178. $this->out($optionParser->epilog());
  179. }
  180. /**
  181. * Override main() to handle action
  182. *
  183. * @param string $command
  184. * @return void
  185. */
  186. public function main($command = null) {
  187. $this->_finished = false;
  188. while (!$this->_finished) {
  189. if (empty($command)) {
  190. $command = trim($this->in(''));
  191. }
  192. $method = $this->_method($command);
  193. if ($method) {
  194. $this->$method($command);
  195. } else {
  196. $this->out(__d('cake_console', "Invalid command"));
  197. $this->out();
  198. }
  199. $command = '';
  200. }
  201. }
  202. /**
  203. * Determine the method to process the current command
  204. *
  205. * @param string $command
  206. * @return string or false
  207. */
  208. protected function _method($command) {
  209. foreach ($this->_methodPatterns as $method => $pattern) {
  210. if (preg_match($pattern, $command)) {
  211. return $method;
  212. }
  213. }
  214. return false;
  215. }
  216. /**
  217. * Set the finiished property so that the loop in main method ends
  218. *
  219. * @return void
  220. */
  221. protected function _exit() {
  222. $this->_finished = true;
  223. }
  224. /**
  225. * List all models
  226. *
  227. * @return void
  228. */
  229. protected function _models() {
  230. $this->out(__d('cake_console', 'Model classes:'));
  231. $this->hr();
  232. foreach ($this->models as $model) {
  233. $this->out(" - {$model}");
  234. }
  235. }
  236. /**
  237. * Bind an association
  238. *
  239. * @param mixed $command
  240. * @return void
  241. */
  242. protected function _bind($command) {
  243. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  244. foreach ($tmp as $data) {
  245. $data = strip_tags($data);
  246. $data = str_replace($this->badCommandChars, "", $data);
  247. }
  248. $modelA = $tmp[1];
  249. $association = $tmp[2];
  250. $modelB = $tmp[3];
  251. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
  252. $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
  253. $this->out(__d('cake_console', "Created %s association between %s and %s",
  254. $association, $modelA, $modelB));
  255. } else {
  256. $this->out(__d('cake_console', "Please verify you are using valid models and association types"));
  257. }
  258. }
  259. /**
  260. * Unbind an association
  261. *
  262. * @param mixed $command
  263. * @return void
  264. */
  265. protected function _unbind($command) {
  266. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  267. foreach ($tmp as $data) {
  268. $data = strip_tags($data);
  269. $data = str_replace($this->badCommandChars, "", $data);
  270. }
  271. $modelA = $tmp[1];
  272. $association = $tmp[2];
  273. $modelB = $tmp[3];
  274. // Verify that there is actually an association to unbind
  275. $currentAssociations = $this->{$modelA}->getAssociated();
  276. $validCurrentAssociation = false;
  277. foreach ($currentAssociations as $model => $currentAssociation) {
  278. if ($model == $modelB && $association == $currentAssociation) {
  279. $validCurrentAssociation = true;
  280. }
  281. }
  282. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
  283. $this->{$modelA}->unbindModel(array($association => array($modelB)));
  284. $this->out(__d('cake_console', "Removed %s association between %s and %s",
  285. $association, $modelA, $modelB));
  286. } else {
  287. $this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
  288. }
  289. }
  290. /**
  291. * Perform a find
  292. *
  293. * @param mixed $command
  294. * @return void
  295. */
  296. protected function _find($command) {
  297. $command = strip_tags($command);
  298. $command = str_replace($this->badCommandChars, "", $command);
  299. // Do we have a valid model?
  300. list($modelToCheck, $tmp) = explode('->', $command);
  301. if ($this->_isValidModel($modelToCheck)) {
  302. $findCommand = "\$data = \$this->$command;";
  303. //@codingStandardsIgnoreStart
  304. @eval($findCommand);
  305. //@codingStandardsIgnoreEnd
  306. if (is_array($data)) {
  307. foreach ($data as $idx => $results) {
  308. if (is_numeric($idx)) { // findAll() output
  309. foreach ($results as $modelName => $result) {
  310. $this->out("$modelName");
  311. foreach ($result as $field => $value) {
  312. if (is_array($value)) {
  313. foreach ($value as $field2 => $value2) {
  314. $this->out("\t$field2: $value2");
  315. }
  316. $this->out();
  317. } else {
  318. $this->out("\t$field: $value");
  319. }
  320. }
  321. }
  322. } else { // find() output
  323. $this->out($idx);
  324. foreach ($results as $field => $value) {
  325. if (is_array($value)) {
  326. foreach ($value as $field2 => $value2) {
  327. $this->out("\t$field2: $value2");
  328. }
  329. $this->out();
  330. } else {
  331. $this->out("\t$field: $value");
  332. }
  333. }
  334. }
  335. }
  336. } else {
  337. $this->out();
  338. $this->out(__d('cake_console', "No result set found"));
  339. }
  340. } else {
  341. $this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
  342. }
  343. }
  344. /**
  345. * Save a record
  346. *
  347. * @param mixed $command
  348. * @return void
  349. */
  350. protected function _save($command) {
  351. // Validate the model we're trying to save here
  352. $command = strip_tags($command);
  353. $command = str_replace($this->badCommandChars, "", $command);
  354. list($modelToSave, $tmp) = explode("->", $command);
  355. if ($this->_isValidModel($modelToSave)) {
  356. // Extract the array of data we are trying to build
  357. list(, $data) = explode("->save", $command);
  358. $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
  359. $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
  360. //@codingStandardsIgnoreStart
  361. @eval($saveCommand);
  362. //@codingStandardsIgnoreEnd
  363. $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
  364. }
  365. }
  366. /**
  367. * Show the columns for a model
  368. *
  369. * @param mixed $command
  370. * @return void
  371. */
  372. protected function _columns($command) {
  373. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  374. $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
  375. if ($this->_isValidModel($modelToCheck)) {
  376. // Get the column info for this model
  377. $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
  378. //@codingStandardsIgnoreStart
  379. @eval($fieldsCommand);
  380. //@codingStandardsIgnoreEnd
  381. if (is_array($data)) {
  382. foreach ($data as $field => $type) {
  383. $this->out("\t{$field}: {$type}");
  384. }
  385. }
  386. } else {
  387. $this->out(__d('cake_console', "Please verify that you selected a valid model"));
  388. }
  389. }
  390. /**
  391. * Reload route definitions
  392. *
  393. * @return void
  394. */
  395. protected function _routesReload() {
  396. if (!$this->_loadRoutes()) {
  397. 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."));
  398. }
  399. $this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count(Router::$routes)));
  400. }
  401. /**
  402. * Show all routes
  403. *
  404. * @return void
  405. */
  406. protected function _routesShow() {
  407. $this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults'), true));
  408. }
  409. /**
  410. * Parse an array URL and show the equivalent URL as a string
  411. *
  412. * @param mixed $command
  413. * @return void
  414. */
  415. protected function _routeToString($command) {
  416. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  417. //@codingStandardsIgnoreStart
  418. if ($url = eval('return array' . $tmp[1] . ';')) {
  419. //@codingStandardsIgnoreEnd
  420. $this->out(Router::url($url));
  421. }
  422. }
  423. /**
  424. * Parse a string URL and show as an array
  425. *
  426. * @param mixed $command
  427. * @return void
  428. */
  429. protected function _routeToArray($command) {
  430. preg_match($this->_methodPatterns[__FUNCTION__], $command, $tmp);
  431. $this->out(var_export(Router::parse($tmp[1]), true));
  432. }
  433. /**
  434. * Tells if the specified model is included in the list of available models
  435. *
  436. * @param string $modelToCheck
  437. * @return boolean true if is an available model, false otherwise
  438. */
  439. protected function _isValidModel($modelToCheck) {
  440. return in_array($modelToCheck, $this->models);
  441. }
  442. /**
  443. * Reloads the routes configuration from app/Config/routes.php, and compiles
  444. * all routes found
  445. *
  446. * @return boolean True if config reload was a success, otherwise false
  447. */
  448. protected function _loadRoutes() {
  449. Router::reload();
  450. extract(Router::getNamedExpressions());
  451. //@codingStandardsIgnoreStart
  452. if (!@include APP . 'Config' . DS . 'routes.php') {
  453. //@codingStandardsIgnoreEnd
  454. return false;
  455. }
  456. CakePlugin::routes();
  457. Router::parse('/');
  458. return true;
  459. }
  460. }