ConsoleShell.php 11 KB

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