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.3 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.3
      • 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
  • ServerShell
  • TestShell
  • TestsuiteShell
  • UpgradeShell
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 11:  * @link          http://cakephp.org CakePHP(tm) Project
 12:  * @since         CakePHP(tm) v 1.2.0.5012
 13:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 14:  */
 15: 
 16: App::uses('AppShell', 'Console/Command');
 17: 
 18: /**
 19:  * Provides a very basic 'interactive' console for CakePHP apps.
 20:  *
 21:  * @package       Cake.Console.Command
 22:  */
 23: class ConsoleShell extends AppShell {
 24: 
 25: /**
 26:  * Available binding types
 27:  *
 28:  * @var array
 29:  */
 30:     public $associations = array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany');
 31: 
 32: /**
 33:  * Chars that describe invalid commands
 34:  *
 35:  * @var array
 36:  */
 37:     public $badCommandChars = array('$', ';');
 38: 
 39: /**
 40:  * Available models
 41:  *
 42:  * @var array
 43:  */
 44:     public $models = array();
 45: 
 46: /**
 47:  * Override startup of the Shell
 48:  *
 49:  * @return void
 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:  * 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:             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:                     // Verify that there is actually an association to unbind
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:                     // Remove any bad info
232:                     $command = strip_tags($command);
233:                     $command = str_replace($this->badCommandChars, "", $command);
234: 
235:                     // Do we have a valid model?
236:                     list($modelToCheck, $tmp) = explode('->', $command);
237: 
238:                     if ($this->_isValidModel($modelToCheck)) {
239:                         $findCommand = "\$data = \$this->$command;";
240:                         //@codingStandardsIgnoreStart
241:                         @eval($findCommand);
242:                         //@codingStandardsIgnoreEnd
243: 
244:                         if (is_array($data)) {
245:                             foreach ($data as $idx => $results) {
246:                                 if (is_numeric($idx)) { // findAll() output
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 { // find() output
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:                     // Validate the model we're trying to save here
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:                         // Extract the array of data we are trying to build
295:                         list(, $data) = explode("->save", $command);
296:                         $data = preg_replace('/^\(*(array)?\(*(.+?)\)*$/i', '\\2', $data);
297:                         $saveCommand = "\$this->{$modelToSave}->save(array('{$modelToSave}' => array({$data})));";
298:                         //@codingStandardsIgnoreStart
299:                         @eval($saveCommand);
300:                         //@codingStandardsIgnoreEnd
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:                         // Get the column info for this model
309:                         $fieldsCommand = "\$data = \$this->{$modelToCheck}->getColumnTypes();";
310:                         //@codingStandardsIgnoreStart
311:                         @eval($fieldsCommand);
312:                         //@codingStandardsIgnoreEnd
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:                     //@codingStandardsIgnoreStart
335:                     if ($url = eval('return array' . $tmp[1] . ';')) {
336:                         //@codingStandardsIgnoreEnd
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:  * Tells if the specified model is included in the list of available models
353:  *
354:  * @param string $modelToCheck
355:  * @return boolean true if is an available model, false otherwise
356:  */
357:     protected function _isValidModel($modelToCheck) {
358:         return in_array($modelToCheck, $this->models);
359:     }
360: 
361: /**
362:  * Reloads the routes configuration from app/Config/routes.php, and compiles
363:  * all routes found
364:  *
365:  * @return boolean True if config reload was a success, otherwise false
366:  */
367:     protected function _loadRoutes() {
368:         Router::reload();
369:         extract(Router::getNamedExpressions());
370: 
371:         //@codingStandardsIgnoreStart
372:         if (!@include APP . 'Config' . DS . 'routes.php') {
373:             //@codingStandardsIgnoreEnd
374:             return false;
375:         }
376:         CakePlugin::routes();
377: 
378:         Router::parse('/');
379:         return true;
380:     }
381: 
382: }
383: 
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