1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14:
15:
16: App::uses('AppShell', 'Console/Command');
17:
18: 19: 20: 21: 22:
23: class ConsoleShell extends AppShell {
24:
25: 26: 27: 28: 29:
30: public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
31:
32: 33: 34: 35: 36:
37: public $badCommandChars = array('$', ';');
38:
39: 40: 41: 42: 43:
44: public $models = array();
45:
46: 47: 48: 49: 50:
51: public function startup() {
52: App::uses('Dispatcher', 'Routing');
53: $this->Dispatcher = new Dispatcher();
54: $this->models = App::objects('Model');
55:
56: foreach ($this->models as $model) {
57: $class = $model;
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: switch (true) {
171: case $command == 'help':
172: $this->help();
173: break;
174: case $command == 'quit':
175: case $command == 'exit':
176: return true;
177: case $command == 'models':
178: $this->out(__d('cake_console', 'Model classes:'));
179: $this->hr();
180: foreach ($this->models as $model) {
181: $this->out(" - {$model}");
182: }
183: break;
184: case preg_match("/^(\w+) bind (\w+) (\w+)/", $command, $tmp):
185: foreach ($tmp as $data) {
186: $data = strip_tags($data);
187: $data = str_replace($this->badCommandChars, "", $data);
188: }
189:
190: $modelA = $tmp[1];
191: $association = $tmp[2];
192: $modelB = $tmp[3];
193:
194: if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations)) {
195: $this->{$modelA}->bindModel(array($association => array($modelB => array('className' => $modelB))), false);
196: $this->out(__d('cake_console', "Created %s association between %s and %s",
197: $association, $modelA, $modelB));
198: } else {
199: $this->out(__d('cake_console', "Please verify you are using valid models and association types"));
200: }
201: break;
202: case preg_match("/^(\w+) unbind (\w+) (\w+)/", $command, $tmp):
203: foreach ($tmp as $data) {
204: $data = strip_tags($data);
205: $data = str_replace($this->badCommandChars, "", $data);
206: }
207:
208: $modelA = $tmp[1];
209: $association = $tmp[2];
210: $modelB = $tmp[3];
211:
212:
213: $currentAssociations = $this->{$modelA}->getAssociated();
214: $validCurrentAssociation = false;
215:
216: foreach ($currentAssociations as $model => $currentAssociation) {
217: if ($model == $modelB && $association == $currentAssociation) {
218: $validCurrentAssociation = true;
219: }
220: }
221:
222: if ($this->_isValidModel($modelA) && $this->_isValidModel($modelB) && in_array($association, $this->associations) && $validCurrentAssociation) {
223: $this->{$modelA}->unbindModel(array($association => array($modelB)));
224: $this->out(__d('cake_console', "Removed %s association between %s and %s",
225: $association, $modelA, $modelB));
226: } else {
227: $this->out(__d('cake_console', "Please verify you are using valid models, valid current association, and valid association types"));
228: }
229: break;
230: case (strpos($command, "->find") > 0):
231:
232: $command = strip_tags($command);
233: $command = str_replace($this->badCommandChars, "", $command);
234:
235:
236: list($modelToCheck, $tmp) = explode('->', $command);
237:
238: if ($this->_isValidModel($modelToCheck)) {
239: $findCommand = "\$data = \$this->$command;";
240:
241: @eval($findCommand);
242:
243:
244: if (is_array($data)) {
245: foreach ($data as $idx => $results) {
246: if (is_numeric($idx)) {
247: foreach ($results as $modelName => $result) {
248: $this->out("$modelName");
249:
250: foreach ($result as $field => $value) {
251: if (is_array($value)) {
252: foreach ($value as $field2 => $value2) {
253: $this->out("\t$field2: $value2");
254: }
255:
256: $this->out();
257: } else {
258: $this->out("\t$field: $value");
259: }
260: }
261: }
262: } else {
263: $this->out($idx);
264:
265: foreach ($results as $field => $value) {
266: if (is_array($value)) {
267: foreach ($value as $field2 => $value2) {
268: $this->out("\t$field2: $value2");
269: }
270:
271: $this->out();
272: } else {
273: $this->out("\t$field: $value");
274: }
275: }
276: }
277: }
278: } else {
279: $this->out();
280: $this->out(__d('cake_console', "No result set found"));
281: }
282: } else {
283: $this->out(__d('cake_console', "%s is not a valid model", $modelToCheck));
284: }
285:
286: break;
287: case (strpos($command, '->save') > 0):
288:
289: $command = strip_tags($command);
290: $command = str_replace($this->badCommandChars, "", $command);
291: list($modelToSave, $tmp) = explode("->", $command);
292:
293: if ($this->_isValidModel($modelToSave)) {
294:
295: list(, $data) = explode("->save", $command);
296: $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
297: $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
298:
299: @eval($saveCommand);
300:
301: $this->out(__d('cake_console', 'Saved record for %s', $modelToSave));
302: }
303: break;
304: case preg_match("/^(\w+) columns/", $command, $tmp):
305: $modelToCheck = strip_tags(str_replace($this->badCommandChars, "", $tmp[1]));
306:
307: if ($this->_isValidModel($modelToCheck)) {
308:
309: $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
310:
311: @eval($fieldsCommand);
312:
313:
314: if (is_array($data)) {
315: foreach ($data as $field => $type) {
316: $this->out("\t{$field}: {$type}");
317: }
318: }
319: } else {
320: $this->out(__d('cake_console', "Please verify that you selected a valid model"));
321: }
322: break;
323: case preg_match("/^routes\s+reload/i", $command, $tmp):
324: if (!$this->_loadRoutes()) {
325: $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."));
326: break;
327: }
328: $this->out(__d('cake_console', "Routes configuration reloaded, %d routes connected", count(Router::$routes)));
329: break;
330: case preg_match("/^routes\s+show/i", $command, $tmp):
331: $this->out(print_r(Hash::combine(Router::$routes, '{n}.template', '{n}.defaults'), true));
332: break;
333: case (preg_match("/^route\s+(\(.*\))$/i", $command, $tmp) == true):
334:
335: if ($url = eval('return array' . $tmp[1] . ';')) {
336:
337: $this->out(Router::url($url));
338: }
339: break;
340: case preg_match("/^route\s+(.*)/i", $command, $tmp):
341: $this->out(var_export(Router::parse($tmp[1]), true));
342: break;
343: default:
344: $this->out(__d('cake_console', "Invalid command"));
345: $this->out();
346: }
347: $command = '';
348: }
349: }
350:
351: 352: 353: 354: 355: 356:
357: protected function _isValidModel($modelToCheck) {
358: return in_array($modelToCheck, $this->models);
359: }
360:
361: 362: 363: 364: 365: 366:
367: protected function _loadRoutes() {
368: Router::reload();
369: extract(Router::getNamedExpressions());
370:
371:
372: if (!@include APP . 'Config' . DS . 'routes.php') {
373:
374: return false;
375: }
376: CakePlugin::routes();
377:
378: Router::parse('/');
379: return true;
380: }
381:
382: }
383: