CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.2 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.2
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AclShell
  • ApiShell
  • BakeShell
  • CommandListShell
  • ConsoleShell
  • I18nShell
  • SchemaShell
  • TestShell
  • TestsuiteShell
  • UpgradeShell
  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: 
 15: App::uses('AppShell', 'Console/Command');
 16: 
 17: /**
 18:  * Provides a very basic 'interactive' console for CakePHP apps.
 19:  *
 20:  * @package       Cake.Console.Command
 21:  */
 22: class ConsoleShell extends AppShell {
 23: 
 24: /**
 25:  * Available binding types
 26:  *
 27:  * @var array
 28:  */
 29:     public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
 30: 
 31: /**
 32:  * Chars that describe invalid commands
 33:  *
 34:  * @var array
 35:  */
 36:     public $badCommandChars = array('$', ';');
 37: 
 38: /**
 39:  * Available models
 40:  *
 41:  * @var array
 42:  */
 43:     public $models = array();
 44: 
 45: /**
 46:  * Override startup of the Shell
 47:  *
 48:  * @return void
 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:  * Prints the help message
151:  *
152:  * @return void
153:  */
154:     public function help() {
155:         $optionParser = $this->getOptionParser();
156:         $this->out($optionParser->epilog());
157:     }
158: 
159: /**
160:  * Override main() to handle action
161:  *
162:  * @param string $command
163:  * @return void
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:                     // Verify that there is actually an association to unbind
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:                     // Remove any bad info
233:                     $command = strip_tags($command);
234:                     $command = str_replace($this->badCommandChars, "", $command);
235: 
236:                     // Do we have a valid model?
237:                     list($modelToCheck, $tmp) = explode('->', $command);
238: 
239:                     if ($this->_isValidModel($modelToCheck)) {
240:                         $findCommand = "\$data = \$this->$command;";
241:                         //@codingStandardsIgnoreStart
242:                         @eval($findCommand);
243:                         //@codingStandardsIgnoreEnd
244: 
245:                         if (is_array($data)) {
246:                             foreach ($data as $idx => $results) {
247:                                 if (is_numeric($idx)) { // findAll() output
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 { // find() output
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:                     // Validate the model we're trying to save here
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:                         // Extract the array of data we are trying to build
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:                         //@codingStandardsIgnoreStart
300:                         @eval($saveCommand);
301:                         //@codingStandardsIgnoreEnd
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:                         // Get the column info for this model
310:                         $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
311:                         //@codingStandardsIgnoreStart
312:                         @eval($fieldsCommand);
313:                         //@codingStandardsIgnoreEnd
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:                     //@codingStandardsIgnoreStart
336:                     if ($url = eval('return array' . $tmp[1] . ';')) {
337:                         //@codingStandardsIgnoreEnd
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:  * Tells if the specified model is included in the list of available models
355:  *
356:  * @param string $modelToCheck
357:  * @return boolean true if is an available model, false otherwise
358:  */
359:     protected function _isValidModel($modelToCheck) {
360:         return in_array($modelToCheck, $this->models);
361:     }
362: 
363: /**
364:  * Reloads the routes configuration from app/Config/routes.php, and compiles
365:  * all routes found
366:  *
367:  * @return boolean True if config reload was a success, otherwise false
368:  */
369:     protected function _loadRoutes() {
370:         Router::reload();
371:         extract(Router::getNamedExpressions());
372: 
373:         //@codingStandardsIgnoreStart
374:         if (!@include APP . 'Config' . DS . 'routes.php') {
375:             //@codingStandardsIgnoreEnd
376:             return false;
377:         }
378:         CakePlugin::routes();
379: 
380:         Router::parse('/');
381:         return true;
382:     }
383: 
384: }
385: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs