1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13:
14:
15: App::uses('AppShell', 'Console/Command');
16:
17: 18: 19: 20: 21:
22: class ConsoleShell extends AppShell {
23:
24: 25: 26: 27: 28:
29: public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
30:
31: 32: 33: 34: 35:
36: public $badCommandChars = array('$', ';');
37:
38: 39: 40: 41: 42:
43: public $models = array();
44:
45: 46: 47: 48: 49:
50: public function startup() {
51: App::uses('Dispatcher', 'Routing');
52: $this->Dispatcher = new Dispatcher();
53: $this->models = App::objects('Model');
54:
55: foreach ($this->models as $model) {
56: $class = $model;
57: $this->models[$model] = $class;
58: App::uses($class, 'Model');
59: $this->{$class} = new $class();
60: }
61: $this->out(__d('cake_console', 'Model classes:'));
62: $this->hr();
63:
64: foreach ($this->models as $model) {
65: $this->out(" - {$model}");
66: }
67:
68: if (!$this->_loadRoutes()) {
69: $message = __d(
70: 'cake_console',
71: 'There was an error loading the routes config. Please check that the file exists and contains no errors.'
72: );
73: $this->err($message);
74: }
75: }
76:
77: public function getOptionParser() {
78: $description = array(
79: 'The interactive console is a tool for testing parts of your',
80: 'app before you write code.',
81: '',
82: 'See below for a list of supported commands.'
83: );
84:
85: $epilog = array(
86: '<info>Model testing</info>',
87: '',
88: 'To test model results, use the name of your model without a leading $',
89: 'e.g. Foo->find("all")',
90: "",
91: 'To dynamically set associations, you can do the following:',
92: '',
93: "\tModelA bind <association> ModelB",
94: '',
95: "where the supported associations are hasOne, hasMany, belongsTo, hasAndBelongsToMany",
96: "",
97: 'To dynamically remove associations, you can do the following:',
98: '',
99: "\t ModelA unbind <association> ModelB",
100: '',
101: "where the supported associations are the same as above",
102: "",
103: "To save a new field in a model, you can do the following:",
104: '',
105: "\tModelA->save(array('foo' => 'bar', 'baz' => 0))",
106: '',
107: "where you are passing a hash of data to be saved in the format",
108: "of field => value pairs",
109: "",
110: "To get column information for a model, use the following:",
111: '',
112: "\tModelA columns",
113: '',
114: "which returns a list of columns and their type",
115: "",
116: '<info>Route testing</info>',
117: "",
118: 'To test URLs against your app\'s route configuration, type:',
119: "",
120: "\tRoute <url>",
121: "",
122: "where url is the path to your your action plus any query parameters,",
123: "minus the application's base path. For example:",
124: "",
125: "\tRoute /posts/view/1",
126: "",
127: "will return something like the following:",
128: "",
129: "\tarray(",
130: "\t [...]",
131: "\t 'controller' => 'posts',",
132: "\t 'action' => 'view',",
133: "\t [...]",
134: "\t)",
135: "",
136: 'Alternatively, you can use simple array syntax to test reverse',
137: 'To reload your routes config (Config/routes.php), do the following:',
138: "",
139: "\tRoutes reload",
140: "",
141: 'To show all connected routes, do the following:',
142: '',
143: "\tRoutes show",
144: );
145: return parent::getOptionParser()
146: ->description($description)
147: ->epilog($epilog);
148: }
149: 150: 151: 152: 153:
154: public function help() {
155: $optionParser = $this->getOptionParser();
156: $this->out($optionParser->epilog());
157: }
158:
159: 160: 161: 162: 163: 164:
165: public function main($command = null) {
166: while (true) {
167: if (empty($command)) {
168: $command = trim($this->in(''));
169: }
170:
171: switch ($command) {
172: case 'help':
173: $this->help();
174: break;
175: case 'quit':
176: case 'exit':
177: return true;
178: case 'models':
179: $this->out(__d('cake_console', 'Model classes:'));
180: $this->hr();
181: foreach ($this->models as $model) {
182: $this->out(" - {$model}");
183: }
184: break;
185: case (preg_match("/^(\w+) bind (\w+) (\w+)/", $command, $tmp) == true):
186: foreach ($tmp as $data) {
187: $data = strip_tags($data);
188: $data = str_replace($this->badCommandChars, "", $data);
189: }
190:
191: $modelA = $tmp[1];
192: $association = $tmp[2];
193: $modelB = $tmp[3];
194:
195: if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
196: $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
197: $this->out(__d('cake_console', "Created %s association between %s and %s",
198: $association, $modelA, $modelB));
199: } else {
200: $this->out(__d('cake_console', "Please verify you are using valid models and association types"));
201: }
202: break;
203: case (preg_match("/^(\w+) unbind (\w+) (\w+)/", $command, $tmp) == true):
204: foreach ($tmp as $data) {
205: $data = strip_tags($data);
206: $data = str_replace($this->badCommandChars, "", $data);
207: }
208:
209: $modelA = $tmp[1];
210: $association = $tmp[2];
211: $modelB = $tmp[3];
212:
213:
214: $currentAssociations = $this->{$modelA}->getAssociated();
215: $validCurrentAssociation = false;
216:
217: foreach ($currentAssociations as $model => $currentAssociation) {
218: if ($model == $modelB && $association == $currentAssociation) {
219: $validCurrentAssociation = true;
220: }
221: }
222:
223: if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
224: $this->{$modelA}->unbindModel(array($association => array($modelB)));
225: $this->out(__d('cake_console', "Removed %s association between %s and %s",
226: $association, $modelA, $modelB));
227: } else {
228: $this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
229: }
230: break;
231: case (strpos($command, "->find") > 0):
232:
233: $command = strip_tags($command);
234: $command = str_replace($this->badCommandChars, "", $command);
235:
236:
237: list($modelToCheck, $tmp) = explode('->', $command);
238:
239: if ($this->_isValidModel($modelToCheck)) {
240: $findCommand = "\$data = \$this->$command;";
241:
242: @eval($findCommand);
243:
244:
245: if (is_array($data)) {
246: foreach ($data as $idx => $results) {
247: if (is_numeric($idx)) {
248: foreach ($results as $modelName => $result) {
249: $this->out("$modelName");
250:
251: foreach ($result as $field => $value) {
252: if (is_array($value)) {
253: foreach ($value as $field2 => $value2) {
254: $this->out("\t$field2: $value2");
255: }
256:
257: $this->out();
258: } else {
259: $this->out("\t$field: $value");
260: }
261: }
262: }
263: } else {
264: $this->out($idx);
265:
266: foreach ($results as $field => $value) {
267: if (is_array($value)) {
268: foreach ($value as $field2 => $value2) {
269: $this->out("\t$field2: $value2");
270: }
271:
272: $this->out();
273: } else {
274: $this->out("\t$field: $value");
275: }
276: }
277: }
278: }
279: } else {
280: $this->out();
281: $this->out(__d('cake_console', "No result set found"));
282: }
283: } else {
284: $this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
285: }
286:
287: break;
288: case (strpos($command, '->save') > 0):
289:
290: $command = strip_tags($command);
291: $command = str_replace($this->badCommandChars, "", $command);
292: list($modelToSave, $tmp) = explode("->", $command);
293:
294: if ($this->_isValidModel($modelToSave)) {
295:
296: list($foo, $data) = explode("->save", $command);
297: $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
298: $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
299:
300: @eval($saveCommand);
301:
302: $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
303: }
304: break;
305: case (preg_match("/^(\w+) columns/", $command, $tmp) == true):
306: $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
307:
308: if ($this->_isValidModel($modelToCheck)) {
309:
310: $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
311:
312: @eval($fieldsCommand);
313:
314:
315: if (is_array($data)) {
316: foreach ($data as $field => $type) {
317: $this->out("\t{$field}: {$type}");
318: }
319: }
320: } else {
321: $this->out(__d('cake_console', "Please verify that you selected a valid model"));
322: }
323: break;
324: case (preg_match("/^routes\s+reload/i", $command, $tmp) == true):
325: if (!$this->_loadRoutes()) {
326: $this->err(__d('cake_console', "There was an error loading the routes config. Please check that the file exists and is free of parse errors."));
327: break;
328: }
329: $this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count(Router::$routes)));
330: break;
331: case (preg_match("/^routes\s+show/i", $command, $tmp) == true):
332: $this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults'), true));
333: break;
334: case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
335:
336: if ($url = eval('return array' . $tmp[1] . ';')) {
337:
338: $this->out(Router::url($url));
339: }
340: break;
341: case (preg_match("/^route\s+(.*)/i", $command, $tmp) == true):
342: $this->out(var_export(Router::parse($tmp[1]), true));
343: break;
344: default:
345: $this->out(__d('cake_console', "Invalid command"));
346: $this->out();
347: break;
348: }
349: $command = '';
350: }
351: }
352:
353: 354: 355: 356: 357: 358:
359: protected function _isValidModel($modelToCheck) {
360: return in_array($modelToCheck, $this->models);
361: }
362:
363: 364: 365: 366: 367: 368:
369: protected function _loadRoutes() {
370: Router::reload();
371: extract(Router::getNamedExpressions());
372:
373:
374: if (!@include APP . 'Config' . DS . 'routes.php') {
375:
376: return false;
377: }
378: CakePlugin::routes();
379:
380: Router::parse('/');
381: return true;
382: }
383:
384: }
385: