ConsoleShell.php 11 KB

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