/cake/console/libs/console.php

https://github.com/hardsshah/bookmarks · PHP · 339 lines · 252 code · 9 blank · 78 comment · 15 complexity · 03921e604e01532f49ad6cf967c1a83d MD5 · raw file

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