ConsoleShell.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. /**
  3. * CakePHP Console Shell
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.2.0.5012
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. /**
  19. * Provides a very basic 'interactive' console for CakePHP apps.
  20. *
  21. * @package Cake.Console.Command
  22. */
  23. class ConsoleShell extends Shell {
  24. /**
  25. * Available binding types
  26. *
  27. * @var array
  28. */
  29. public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
  30. /**
  31. * Chars that describe invalid commands
  32. *
  33. * @var array
  34. */
  35. public $badCommandChars = array('$', ';');
  36. /**
  37. * Available models
  38. *
  39. * @var array
  40. */
  41. public $models = array();
  42. /**
  43. * Override initialize of the Shell
  44. *
  45. * @return void
  46. */
  47. public function initialize() {
  48. App::uses('Dispatcher', 'Routing');
  49. $this->Dispatcher = new Dispatcher();
  50. $this->models = App::objects('Model');
  51. foreach ($this->models as $model) {
  52. $class = $model;
  53. $this->models[$model] = $class;
  54. App::uses($class, 'Model');
  55. $this->{$class} = new $class();
  56. }
  57. $this->out(__d('cake_console', 'Model classes:'));
  58. $this->hr();
  59. foreach ($this->models as $model) {
  60. $this->out(" - {$model}");
  61. }
  62. $this->_loadRoutes();
  63. }
  64. /**
  65. * Prints the help message
  66. *
  67. * @return void
  68. */
  69. public function help() {
  70. $out = 'Console help:';
  71. $out .= '-------------';
  72. $out .= 'The interactive console is a tool for testing parts of your app before you';
  73. $out .= 'write code.';
  74. $out .= "\n";
  75. $out .= 'Model testing:';
  76. $out .= 'To test model results, use the name of your model without a leading $';
  77. $out .= 'e.g. Foo->find("all")';
  78. $out .= "\n";
  79. $out .= 'To dynamically set associations, you can do the following:';
  80. $out .= "\tModelA bind <association> ModelB";
  81. $out .= "where the supported assocations are hasOne, hasMany, belongsTo, hasAndBelongsToMany";
  82. $out .= "\n";
  83. $out .= 'To dynamically remove associations, you can do the following:';
  84. $out .= "\t ModelA unbind <association> ModelB";
  85. $out .= "where the supported associations are the same as above";
  86. $out .= "\n";
  87. $out .= "To save a new field in a model, you can do the following:";
  88. $out .= "\tModelA->save(array('foo' => 'bar', 'baz' => 0))";
  89. $out .= "where you are passing a hash of data to be saved in the format";
  90. $out .= "of field => value pairs";
  91. $out .= "\n";
  92. $out .= "To get column information for a model, use the following:";
  93. $out .= "\tModelA columns";
  94. $out .= "which returns a list of columns and their type";
  95. $out .= "\n";
  96. $out .= "\n";
  97. $out .= 'Route testing:';
  98. $out .= "\n";
  99. $out .= 'To test URLs against your app\'s route configuration, type:';
  100. $out .= "\n";
  101. $out .= "\tRoute <url>";
  102. $out .= "\n";
  103. $out .= "where url is the path to your your action plus any query parameters,";
  104. $out .= "minus the application's base path. For example:";
  105. $out .= "\n";
  106. $out .= "\tRoute /posts/view/1";
  107. $out .= "\n";
  108. $out .= "will return something like the following:";
  109. $out .= "\n";
  110. $out .= "\tarray (";
  111. $out .= "\t [...]";
  112. $out .= "\t 'controller' => 'posts',";
  113. $out .= "\t 'action' => 'view',";
  114. $out .= "\t [...]";
  115. $out .= "\t)";
  116. $out .= "\n";
  117. $out .= 'Alternatively, you can use simple array syntax to test reverse';
  118. $out .= 'To reload your routes config (Config/routes.php), do the following:';
  119. $out .= "\n";
  120. $out .= "\tRoutes reload";
  121. $out .= "\n";
  122. $out .= 'To show all connected routes, do the following:';
  123. $out .= "\tRoutes show";
  124. $this->out($out);
  125. }
  126. /**
  127. * Override main() to handle action
  128. *
  129. * @param string $command
  130. * @return void
  131. */
  132. public function main($command = null) {
  133. while (true) {
  134. if (empty($command)) {
  135. $command = trim($this->in(''));
  136. }
  137. switch ($command) {
  138. case 'help':
  139. $this->help();
  140. break;
  141. case 'quit':
  142. case 'exit':
  143. return true;
  144. break;
  145. case 'models':
  146. $this->out(__d('cake_console', 'Model classes:'));
  147. $this->hr();
  148. foreach ($this->models as $model) {
  149. $this->out(" - {$model}");
  150. }
  151. break;
  152. case (preg_match("/^(\w+) bind (\w+) (\w+)/", $command, $tmp) == true):
  153. foreach ($tmp as $data) {
  154. $data = strip_tags($data);
  155. $data = str_replace($this->badCommandChars, "", $data);
  156. }
  157. $modelA = $tmp[1];
  158. $association = $tmp[2];
  159. $modelB = $tmp[3];
  160. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
  161. $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
  162. $this->out(__d('cake_console', "Created %s association between %s and %s",
  163. $association, $modelA, $modelB));
  164. } else {
  165. $this->out(__d('cake_console', "Please verify you are using valid models and association types"));
  166. }
  167. break;
  168. case (preg_match("/^(\w+) unbind (\w+) (\w+)/", $command, $tmp) == true):
  169. foreach ($tmp as $data) {
  170. $data = strip_tags($data);
  171. $data = str_replace($this->badCommandChars, "", $data);
  172. }
  173. $modelA = $tmp[1];
  174. $association = $tmp[2];
  175. $modelB = $tmp[3];
  176. // Verify that there is actually an association to unbind
  177. $currentAssociations = $this->{$modelA}->getAssociated();
  178. $validCurrentAssociation = false;
  179. foreach ($currentAssociations as $model => $currentAssociation) {
  180. if ($model == $modelB && $association == $currentAssociation) {
  181. $validCurrentAssociation = true;
  182. }
  183. }
  184. if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
  185. $this->{$modelA}->unbindModel(array($association => array($modelB)));
  186. $this->out(__d('cake_console', "Removed %s association between %s and %s",
  187. $association, $modelA, $modelB));
  188. } else {
  189. $this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
  190. }
  191. break;
  192. case (strpos($command, "->find") > 0):
  193. // Remove any bad info
  194. $command = strip_tags($command);
  195. $command = str_replace($this->badCommandChars, "", $command);
  196. // Do we have a valid model?
  197. list($modelToCheck, $tmp) = explode('->', $command);
  198. if ($this->_isValidModel($modelToCheck)) {
  199. $findCommand = "\$data = \$this->$command;";
  200. @eval($findCommand);
  201. if (is_array($data)) {
  202. foreach ($data as $idx => $results) {
  203. if (is_numeric($idx)) { // findAll() output
  204. foreach ($results as $modelName => $result) {
  205. $this->out("$modelName");
  206. foreach ($result as $field => $value) {
  207. if (is_array($value)) {
  208. foreach ($value as $field2 => $value2) {
  209. $this->out("\t$field2: $value2");
  210. }
  211. $this->out();
  212. } else {
  213. $this->out("\t$field: $value");
  214. }
  215. }
  216. }
  217. } else { // find() output
  218. $this->out($idx);
  219. foreach ($results as $field => $value) {
  220. if (is_array($value)) {
  221. foreach ($value as $field2 => $value2) {
  222. $this->out("\t$field2: $value2");
  223. }
  224. $this->out();
  225. } else {
  226. $this->out("\t$field: $value");
  227. }
  228. }
  229. }
  230. }
  231. } else {
  232. $this->out();
  233. $this->out(__d('cake_console', "No result set found"));
  234. }
  235. } else {
  236. $this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
  237. }
  238. break;
  239. case (strpos($command, '->save') > 0):
  240. // Validate the model we're trying to save here
  241. $command = strip_tags($command);
  242. $command = str_replace($this->badCommandChars, "", $command);
  243. list($modelToSave, $tmp) = explode("->", $command);
  244. if ($this->_isValidModel($modelToSave)) {
  245. // Extract the array of data we are trying to build
  246. list($foo, $data) = explode("->save", $command);
  247. $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
  248. $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
  249. @eval($saveCommand);
  250. $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
  251. }
  252. break;
  253. case (preg_match("/^(\w+) columns/", $command, $tmp) == true):
  254. $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
  255. if ($this->_isValidModel($modelToCheck)) {
  256. // Get the column info for this model
  257. $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
  258. @eval($fieldsCommand);
  259. if (is_array($data)) {
  260. foreach ($data as $field => $type) {
  261. $this->out("\t{$field}: {$type}");
  262. }
  263. }
  264. } else {
  265. $this->out(__d('cake_console', "Please verify that you selected a valid model"));
  266. }
  267. break;
  268. case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
  269. $router = Router::getInstance();
  270. if (!$this->_loadRoutes()) {
  271. $this->out(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
  272. break;
  273. }
  274. $this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count($router->routes)));
  275. break;
  276. case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
  277. $router = Router::getInstance();
  278. $this->out(implode("\n", Set::extract($router->routes, '{n}.0')));
  279. break;
  280. case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
  281. if ($url = eval('return array' . $tmp[1] . ';')) {
  282. $this->out(Router::url($url));
  283. }
  284. break;
  285. case (preg_match("/^route\s+(.*)/i", $command, $tmp) == true):
  286. $this->out(var_export(Router::parse($tmp[1]), true));
  287. break;
  288. default:
  289. $this->out(__d('cake_console', "Invalid command"));
  290. $this->out();
  291. break;
  292. }
  293. $command = '';
  294. }
  295. }
  296. /**
  297. * Tells if the specified model is included in the list of available models
  298. *
  299. * @param string $modelToCheck
  300. * @return boolean true if is an available model, false otherwise
  301. */
  302. protected function _isValidModel($modelToCheck) {
  303. return in_array($modelToCheck, $this->models);
  304. }
  305. /**
  306. * Reloads the routes configuration from app/Config/routes.php, and compiles
  307. * all routes found
  308. *
  309. * @return boolean True if config reload was a success, otherwise false
  310. */
  311. protected function _loadRoutes() {
  312. Router::reload();
  313. extract(Router::getNamedExpressions());
  314. if (!@include(APP . 'Config' . DS . 'routes.php')) {
  315. return false;
  316. }
  317. CakePlugin::routes();
  318. Router::parse('/');
  319. foreach (array_keys(Router::getNamedExpressions()) as $var) {
  320. unset(${$var});
  321. }
  322. foreach (Router::$routes as $route) {
  323. $route->compile();
  324. }
  325. return true;
  326. }
  327. }