PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/Command/ConsoleShell.php

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