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

  • BakeTask
  • ControllerTask
  • DbConfigTask
  • ExtractTask
  • FixtureTask
  • ModelTask
  • PluginTask
  • ProjectTask
  • TemplateTask
  • TestTask
  • ViewTask
  1: <?php
  2: /**
  3:  * The ModelTask handles creating and updating models files.
  4:  *
  5:  * PHP 5
  6:  *
  7:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9:  *
 10:  * Licensed under The MIT License
 11:  * For full copyright and license information, please see the LICENSE.txt
 12:  * Redistributions of files must retain the above copyright notice.
 13:  *
 14:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 15:  * @link          http://cakephp.org CakePHP(tm) Project
 16:  * @since         CakePHP(tm) v 1.2
 17:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 18:  */
 19: 
 20: App::uses('AppShell', 'Console/Command');
 21: App::uses('BakeTask', 'Console/Command/Task');
 22: App::uses('ConnectionManager', 'Model');
 23: App::uses('Model', 'Model');
 24: App::uses('Validation', 'Utility');
 25: 
 26: /**
 27:  * Task class for creating and updating model files.
 28:  *
 29:  * @package    Cake.Console.Command.Task
 30:  */
 31: class ModelTask extends BakeTask {
 32: 
 33: /**
 34:  * path to Model directory
 35:  *
 36:  * @var string
 37:  */
 38:     public $path = null;
 39: 
 40: /**
 41:  * tasks
 42:  *
 43:  * @var array
 44:  */
 45:     public $tasks = array('DbConfig', 'Fixture', 'Test', 'Template');
 46: 
 47: /**
 48:  * Tables to skip when running all()
 49:  *
 50:  * @var array
 51:  */
 52:     public $skipTables = array('i18n');
 53: 
 54: /**
 55:  * Holds tables found on connection.
 56:  *
 57:  * @var array
 58:  */
 59:     protected $_tables = array();
 60: 
 61: /**
 62:  * Holds the model names
 63:  *
 64:  * @var array
 65:  */
 66:     protected $_modelNames = array();
 67: 
 68: /**
 69:  * Holds validation method map.
 70:  *
 71:  * @var array
 72:  */
 73:     protected $_validations = array();
 74: 
 75: /**
 76:  * Override initialize
 77:  *
 78:  * @return void
 79:  */
 80:     public function initialize() {
 81:         $this->path = current(App::path('Model'));
 82:     }
 83: 
 84: /**
 85:  * Execution method always used for tasks
 86:  *
 87:  * @return void
 88:  */
 89:     public function execute() {
 90:         parent::execute();
 91: 
 92:         if (empty($this->args)) {
 93:             $this->_interactive();
 94:         }
 95: 
 96:         if (!empty($this->args[0])) {
 97:             $this->interactive = false;
 98:             if (!isset($this->connection)) {
 99:                 $this->connection = 'default';
100:             }
101:             if (strtolower($this->args[0]) === 'all') {
102:                 return $this->all();
103:             }
104:             $model = $this->_modelName($this->args[0]);
105:             $this->listAll($this->connection);
106:             $useTable = $this->getTable($model);
107:             $object = $this->_getModelObject($model, $useTable);
108:             if ($this->bake($object, false)) {
109:                 if ($this->_checkUnitTest()) {
110:                     $this->bakeFixture($model, $useTable);
111:                     $this->bakeTest($model);
112:                 }
113:             }
114:         }
115:     }
116: 
117: /**
118:  * Bake all models at once.
119:  *
120:  * @return void
121:  */
122:     public function all() {
123:         $this->listAll($this->connection, false);
124:         $unitTestExists = $this->_checkUnitTest();
125:         foreach ($this->_tables as $table) {
126:             if (in_array($table, $this->skipTables)) {
127:                 continue;
128:             }
129:             $modelClass = Inflector::classify($table);
130:             $this->out(__d('cake_console', 'Baking %s', $modelClass));
131:             $object = $this->_getModelObject($modelClass, $table);
132:             if ($this->bake($object, false) && $unitTestExists) {
133:                 $this->bakeFixture($modelClass, $table);
134:                 $this->bakeTest($modelClass);
135:             }
136:         }
137:     }
138: 
139: /**
140:  * Get a model object for a class name.
141:  *
142:  * @param string $className Name of class you want model to be.
143:  * @param string $table Table name
144:  * @return Model Model instance
145:  */
146:     protected function _getModelObject($className, $table = null) {
147:         if (!$table) {
148:             $table = Inflector::tableize($className);
149:         }
150:         $object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
151:         $fields = $object->schema(true);
152:         foreach ($fields as $name => $field) {
153:             if (isset($field['key']) && $field['key'] === 'primary') {
154:                 $object->primaryKey = $name;
155:                 break;
156:             }
157:         }
158:         return $object;
159:     }
160: 
161: /**
162:  * Generate a key value list of options and a prompt.
163:  *
164:  * @param array $options Array of options to use for the selections. indexes must start at 0
165:  * @param string $prompt Prompt to use for options list.
166:  * @param integer $default The default option for the given prompt.
167:  * @return integer result of user choice.
168:  */
169:     public function inOptions($options, $prompt = null, $default = null) {
170:         $valid = false;
171:         $max = count($options);
172:         while (!$valid) {
173:             $len = strlen(count($options) + 1);
174:             foreach ($options as $i => $option) {
175:                 $this->out(sprintf("%${len}d. %s", $i + 1, $option));
176:             }
177:             if (empty($prompt)) {
178:                 $prompt = __d('cake_console', 'Make a selection from the choices above');
179:             }
180:             $choice = $this->in($prompt, null, $default);
181:             if (intval($choice) > 0 && intval($choice) <= $max) {
182:                 $valid = true;
183:             }
184:         }
185:         return $choice - 1;
186:     }
187: 
188: /**
189:  * Handles interactive baking
190:  *
191:  * @return boolean
192:  */
193:     protected function _interactive() {
194:         $this->hr();
195:         $this->out(__d('cake_console', "Bake Model\nPath: %s", $this->getPath()));
196:         $this->hr();
197:         $this->interactive = true;
198: 
199:         $primaryKey = 'id';
200:         $validate = $associations = array();
201: 
202:         if (empty($this->connection)) {
203:             $this->connection = $this->DbConfig->getConfig();
204:         }
205:         $currentModelName = $this->getName();
206:         $useTable = $this->getTable($currentModelName);
207:         $db = ConnectionManager::getDataSource($this->connection);
208:         $fullTableName = $db->fullTableName($useTable);
209:         if (!in_array($useTable, $this->_tables)) {
210:             $prompt = __d('cake_console', "The table %s doesn't exist or could not be automatically detected\ncontinue anyway?", $useTable);
211:             $continue = $this->in($prompt, array('y', 'n'));
212:             if (strtolower($continue) === 'n') {
213:                 return false;
214:             }
215:         }
216: 
217:         $tempModel = new Model(array('name' => $currentModelName, 'table' => $useTable, 'ds' => $this->connection));
218: 
219:         $knownToExist = false;
220:         try {
221:             $fields = $tempModel->schema(true);
222:             $knownToExist = true;
223:         } catch (Exception $e) {
224:             $fields = array($tempModel->primaryKey);
225:         }
226:         if (!array_key_exists('id', $fields)) {
227:             $primaryKey = $this->findPrimaryKey($fields);
228:         }
229: 
230:         if ($knownToExist) {
231:             $displayField = $tempModel->hasField(array('name', 'title'));
232:             if (!$displayField) {
233:                 $displayField = $this->findDisplayField($tempModel->schema());
234:             }
235: 
236:             $prompt = __d('cake_console', "Would you like to supply validation criteria \nfor the fields in your model?");
237:             $wannaDoValidation = $this->in($prompt, array('y', 'n'), 'y');
238:             if (array_search($useTable, $this->_tables) !== false && strtolower($wannaDoValidation) === 'y') {
239:                 $validate = $this->doValidation($tempModel);
240:             }
241: 
242:             $prompt = __d('cake_console', "Would you like to define model associations\n(hasMany, hasOne, belongsTo, etc.)?");
243:             $wannaDoAssoc = $this->in($prompt, array('y', 'n'), 'y');
244:             if (strtolower($wannaDoAssoc) === 'y') {
245:                 $associations = $this->doAssociations($tempModel);
246:             }
247:         }
248: 
249:         $this->out();
250:         $this->hr();
251:         $this->out(__d('cake_console', 'The following Model will be created:'));
252:         $this->hr();
253:         $this->out(__d('cake_console', "Name:       %s", $currentModelName));
254: 
255:         if ($this->connection !== 'default') {
256:             $this->out(__d('cake_console', "DB Config:  %s", $this->connection));
257:         }
258:         if ($fullTableName !== Inflector::tableize($currentModelName)) {
259:             $this->out(__d('cake_console', 'DB Table:   %s', $fullTableName));
260:         }
261:         if ($primaryKey !== 'id') {
262:             $this->out(__d('cake_console', 'Primary Key: %s', $primaryKey));
263:         }
264:         if (!empty($validate)) {
265:             $this->out(__d('cake_console', 'Validation: %s', print_r($validate, true)));
266:         }
267:         if (!empty($associations)) {
268:             $this->out(__d('cake_console', 'Associations:'));
269:             $assocKeys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
270:             foreach ($assocKeys as $assocKey) {
271:                 $this->_printAssociation($currentModelName, $assocKey, $associations);
272:             }
273:         }
274: 
275:         $this->hr();
276:         $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
277: 
278:         if (strtolower($looksGood) === 'y') {
279:             $vars = compact('associations', 'validate', 'primaryKey', 'useTable', 'displayField');
280:             $vars['useDbConfig'] = $this->connection;
281:             if ($this->bake($currentModelName, $vars)) {
282:                 if ($this->_checkUnitTest()) {
283:                     $this->bakeFixture($currentModelName, $useTable);
284:                     $this->bakeTest($currentModelName, $useTable, $associations);
285:                 }
286:             }
287:         } else {
288:             return false;
289:         }
290:     }
291: 
292: /**
293:  * Print out all the associations of a particular type
294:  *
295:  * @param string $modelName Name of the model relations belong to.
296:  * @param string $type Name of association you want to see. i.e. 'belongsTo'
297:  * @param string $associations Collection of associations.
298:  * @return void
299:  */
300:     protected function _printAssociation($modelName, $type, $associations) {
301:         if (!empty($associations[$type])) {
302:             for ($i = 0, $len = count($associations[$type]); $i < $len; $i++) {
303:                 $out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
304:                 $this->out($out);
305:             }
306:         }
307:     }
308: 
309: /**
310:  * Finds a primary Key in a list of fields.
311:  *
312:  * @param array $fields Array of fields that might have a primary key.
313:  * @return string Name of field that is a primary key.
314:  */
315:     public function findPrimaryKey($fields) {
316:         $name = 'id';
317:         foreach ($fields as $name => $field) {
318:             if (isset($field['key']) && $field['key'] === 'primary') {
319:                 break;
320:             }
321:         }
322:         return $this->in(__d('cake_console', 'What is the primaryKey?'), null, $name);
323:     }
324: 
325: /**
326:  * interact with the user to find the displayField value for a model.
327:  *
328:  * @param array $fields Array of fields to look for and choose as a displayField
329:  * @return mixed Name of field to use for displayField or false if the user declines to choose
330:  */
331:     public function findDisplayField($fields) {
332:         $fieldNames = array_keys($fields);
333:         $prompt = __d('cake_console', "A displayField could not be automatically detected\nwould you like to choose one?");
334:         $continue = $this->in($prompt, array('y', 'n'));
335:         if (strtolower($continue) === 'n') {
336:             return false;
337:         }
338:         $prompt = __d('cake_console', 'Choose a field from the options above:');
339:         $choice = $this->inOptions($fieldNames, $prompt);
340:         return $fieldNames[$choice];
341:     }
342: 
343: /**
344:  * Handles Generation and user interaction for creating validation.
345:  *
346:  * @param Model $model Model to have validations generated for.
347:  * @return array $validate Array of user selected validations.
348:  */
349:     public function doValidation($model) {
350:         if (!is_object($model)) {
351:             return false;
352:         }
353:         $fields = $model->schema();
354: 
355:         if (empty($fields)) {
356:             return false;
357:         }
358:         $validate = array();
359:         $this->initValidations();
360:         foreach ($fields as $fieldName => $field) {
361:             $validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
362:             if (!empty($validation)) {
363:                 $validate[$fieldName] = $validation;
364:             }
365:         }
366:         return $validate;
367:     }
368: 
369: /**
370:  * Populate the _validations array
371:  *
372:  * @return void
373:  */
374:     public function initValidations() {
375:         $options = $choices = array();
376:         if (class_exists('Validation')) {
377:             $options = get_class_methods('Validation');
378:         }
379:         sort($options);
380:         $default = 1;
381:         foreach ($options as $option) {
382:             if ($option{0} !== '_') {
383:                 $choices[$default] = strtolower($option);
384:                 $default++;
385:             }
386:         }
387:         $choices[$default] = 'none'; // Needed since index starts at 1
388:         $this->_validations = $choices;
389:         return $choices;
390:     }
391: 
392: /**
393:  * Does individual field validation handling.
394:  *
395:  * @param string $fieldName Name of field to be validated.
396:  * @param array $metaData metadata for field
397:  * @param string $primaryKey
398:  * @return array Array of validation for the field.
399:  */
400:     public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
401:         $defaultChoice = count($this->_validations);
402:         $validate = $alreadyChosen = array();
403: 
404:         $anotherValidator = 'y';
405:         while ($anotherValidator === 'y') {
406:             if ($this->interactive) {
407:                 $this->out();
408:                 $this->out(__d('cake_console', 'Field: <info>%s</info>', $fieldName));
409:                 $this->out(__d('cake_console', 'Type: <info>%s</info>', $metaData['type']));
410:                 $this->hr();
411:                 $this->out(__d('cake_console', 'Please select one of the following validation options:'));
412:                 $this->hr();
413: 
414:                 $optionText = '';
415:                 for ($i = 1, $m = $defaultChoice / 2; $i <= $m; $i++) {
416:                     $line = sprintf("%2d. %s", $i, $this->_validations[$i]);
417:                     $optionText .= $line . str_repeat(" ", 31 - strlen($line));
418:                     if ($m + $i !== $defaultChoice) {
419:                         $optionText .= sprintf("%2d. %s\n", $m + $i, $this->_validations[$m + $i]);
420:                     }
421:                 }
422:                 $this->out($optionText);
423:                 $this->out(__d('cake_console', "%s - Do not do any validation on this field.", $defaultChoice));
424:                 $this->hr();
425:             }
426: 
427:             $prompt = __d('cake_console', "... or enter in a valid regex validation string.\n");
428:             $methods = array_flip($this->_validations);
429:             $guess = $defaultChoice;
430:             if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
431:                 if ($fieldName === 'email') {
432:                     $guess = $methods['email'];
433:                 } elseif ($metaData['type'] === 'string' && $metaData['length'] == 36) {
434:                     $guess = $methods['uuid'];
435:                 } elseif ($metaData['type'] === 'string') {
436:                     $guess = $methods['notempty'];
437:                 } elseif ($metaData['type'] === 'text') {
438:                     $guess = $methods['notempty'];
439:                 } elseif ($metaData['type'] === 'integer') {
440:                     $guess = $methods['numeric'];
441:                 } elseif ($metaData['type'] === 'boolean') {
442:                     $guess = $methods['boolean'];
443:                 } elseif ($metaData['type'] === 'date') {
444:                     $guess = $methods['date'];
445:                 } elseif ($metaData['type'] === 'time') {
446:                     $guess = $methods['time'];
447:                 } elseif ($metaData['type'] === 'datetime') {
448:                     $guess = $methods['datetime'];
449:                 } elseif ($metaData['type'] === 'inet') {
450:                     $guess = $methods['ip'];
451:                 }
452:             }
453: 
454:             if ($this->interactive === true) {
455:                 $choice = $this->in($prompt, null, $guess);
456:                 if (in_array($choice, $alreadyChosen)) {
457:                     $this->out(__d('cake_console', "You have already chosen that validation rule,\nplease choose again"));
458:                     continue;
459:                 }
460:                 if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
461:                     $this->out(__d('cake_console', 'Please make a valid selection.'));
462:                     continue;
463:                 }
464:                 $alreadyChosen[] = $choice;
465:             } else {
466:                 $choice = $guess;
467:             }
468: 
469:             if (isset($this->_validations[$choice])) {
470:                 $validatorName = $this->_validations[$choice];
471:             } else {
472:                 $validatorName = Inflector::slug($choice);
473:             }
474: 
475:             if ($choice != $defaultChoice) {
476:                 $validate[$validatorName] = $choice;
477:                 if (is_numeric($choice) && isset($this->_validations[$choice])) {
478:                     $validate[$validatorName] = $this->_validations[$choice];
479:                 }
480:             }
481:             $anotherValidator = 'n';
482:             if ($this->interactive && $choice != $defaultChoice) {
483:                 $anotherValidator = $this->in(__d('cake_console', 'Would you like to add another validation rule?'), array('y', 'n'), 'n');
484:             }
485:         }
486:         return $validate;
487:     }
488: 
489: /**
490:  * Handles associations
491:  *
492:  * @param Model $model
493:  * @return array $associations
494:  */
495:     public function doAssociations($model) {
496:         if (!is_object($model)) {
497:             return false;
498:         }
499:         if ($this->interactive === true) {
500:             $this->out(__d('cake_console', 'One moment while the associations are detected.'));
501:         }
502: 
503:         $fields = $model->schema(true);
504:         if (empty($fields)) {
505:             return array();
506:         }
507: 
508:         if (empty($this->_tables)) {
509:             $this->_tables = (array)$this->getAllTables();
510:         }
511: 
512:         $associations = array(
513:             'belongsTo' => array(),
514:             'hasMany' => array(),
515:             'hasOne' => array(),
516:             'hasAndBelongsToMany' => array()
517:         );
518: 
519:         $associations = $this->findBelongsTo($model, $associations);
520:         $associations = $this->findHasOneAndMany($model, $associations);
521:         $associations = $this->findHasAndBelongsToMany($model, $associations);
522: 
523:         if ($this->interactive !== true) {
524:             unset($associations['hasOne']);
525:         }
526: 
527:         if ($this->interactive === true) {
528:             $this->hr();
529:             if (empty($associations)) {
530:                 $this->out(__d('cake_console', 'None found.'));
531:             } else {
532:                 $this->out(__d('cake_console', 'Please confirm the following associations:'));
533:                 $this->hr();
534:                 $associations = $this->confirmAssociations($model, $associations);
535:             }
536:             $associations = $this->doMoreAssociations($model, $associations);
537:         }
538:         return $associations;
539:     }
540: 
541: /**
542:  * Find belongsTo relations and add them to the associations list.
543:  *
544:  * @param Model $model Model instance of model being generated.
545:  * @param array $associations Array of in progress associations
546:  * @return array $associations with belongsTo added in.
547:  */
548:     public function findBelongsTo(Model $model, $associations) {
549:         $fieldNames = array_keys($model->schema(true));
550:         foreach ($fieldNames as $fieldName) {
551:             $offset = strpos($fieldName, '_id');
552:             if ($fieldName != $model->primaryKey && $fieldName !== 'parent_id' && $offset !== false) {
553:                 $tmpModelName = $this->_modelNameFromKey($fieldName);
554:                 $associations['belongsTo'][] = array(
555:                     'alias' => $tmpModelName,
556:                     'className' => $tmpModelName,
557:                     'foreignKey' => $fieldName,
558:                 );
559:             } elseif ($fieldName === 'parent_id') {
560:                 $associations['belongsTo'][] = array(
561:                     'alias' => 'Parent' . $model->name,
562:                     'className' => $model->name,
563:                     'foreignKey' => $fieldName,
564:                 );
565:             }
566:         }
567:         return $associations;
568:     }
569: 
570: /**
571:  * Find the hasOne and hasMany relations and add them to associations list
572:  *
573:  * @param Model $model Model instance being generated
574:  * @param array $associations Array of in progress associations
575:  * @return array $associations with hasOne and hasMany added in.
576:  */
577:     public function findHasOneAndMany(Model $model, $associations) {
578:         $foreignKey = $this->_modelKey($model->name);
579:         foreach ($this->_tables as $otherTable) {
580:             $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
581:             $tempFieldNames = array_keys($tempOtherModel->schema(true));
582: 
583:             $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
584:             $possibleJoinTable = preg_match($pattern, $otherTable);
585:             if ($possibleJoinTable) {
586:                 continue;
587:             }
588:             foreach ($tempFieldNames as $fieldName) {
589:                 $assoc = false;
590:                 if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
591:                     $assoc = array(
592:                         'alias' => $tempOtherModel->name,
593:                         'className' => $tempOtherModel->name,
594:                         'foreignKey' => $fieldName
595:                     );
596:                 } elseif ($otherTable == $model->table && $fieldName === 'parent_id') {
597:                     $assoc = array(
598:                         'alias' => 'Child' . $model->name,
599:                         'className' => $model->name,
600:                         'foreignKey' => $fieldName
601:                     );
602:                 }
603:                 if ($assoc) {
604:                     $associations['hasOne'][] = $assoc;
605:                     $associations['hasMany'][] = $assoc;
606:                 }
607: 
608:             }
609:         }
610:         return $associations;
611:     }
612: 
613: /**
614:  * Find the hasAndBelongsToMany relations and add them to associations list
615:  *
616:  * @param Model $model Model instance being generated
617:  * @param array $associations Array of in-progress associations
618:  * @return array $associations with hasAndBelongsToMany added in.
619:  */
620:     public function findHasAndBelongsToMany(Model $model, $associations) {
621:         $foreignKey = $this->_modelKey($model->name);
622:         foreach ($this->_tables as $otherTable) {
623:             $tableName = null;
624:             $offset = strpos($otherTable, $model->table . '_');
625:             $otherOffset = strpos($otherTable, '_' . $model->table);
626: 
627:             if ($offset !== false) {
628:                 $tableName = substr($otherTable, strlen($model->table . '_'));
629:             } elseif ($otherOffset !== false) {
630:                 $tableName = substr($otherTable, 0, $otherOffset);
631:             }
632:             if ($tableName && in_array($tableName, $this->_tables)) {
633:                 $habtmName = $this->_modelName($tableName);
634:                 $associations['hasAndBelongsToMany'][] = array(
635:                     'alias' => $habtmName,
636:                     'className' => $habtmName,
637:                     'foreignKey' => $foreignKey,
638:                     'associationForeignKey' => $this->_modelKey($habtmName),
639:                     'joinTable' => $otherTable
640:                 );
641:             }
642:         }
643:         return $associations;
644:     }
645: 
646: /**
647:  * Interact with the user and confirm associations.
648:  *
649:  * @param array $model Temporary Model instance.
650:  * @param array $associations Array of associations to be confirmed.
651:  * @return array Array of confirmed associations
652:  */
653:     public function confirmAssociations(Model $model, $associations) {
654:         foreach ($associations as $type => $settings) {
655:             if (!empty($associations[$type])) {
656:                 foreach ($associations[$type] as $i => $assoc) {
657:                     $prompt = "{$model->name} {$type} {$assoc['alias']}?";
658:                     $response = $this->in($prompt, array('y', 'n'), 'y');
659: 
660:                     if (strtolower($response) === 'n') {
661:                         unset($associations[$type][$i]);
662:                     } elseif ($type === 'hasMany') {
663:                         unset($associations['hasOne'][$i]);
664:                     }
665:                 }
666:                 $associations[$type] = array_merge($associations[$type]);
667:             }
668:         }
669:         return $associations;
670:     }
671: 
672: /**
673:  * Interact with the user and generate additional non-conventional associations
674:  *
675:  * @param Model $model Temporary model instance
676:  * @param array $associations Array of associations.
677:  * @return array Array of associations.
678:  */
679:     public function doMoreAssociations(Model $model, $associations) {
680:         $prompt = __d('cake_console', 'Would you like to define some additional model associations?');
681:         $wannaDoMoreAssoc = $this->in($prompt, array('y', 'n'), 'n');
682:         $possibleKeys = $this->_generatePossibleKeys();
683:         while (strtolower($wannaDoMoreAssoc) === 'y') {
684:             $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
685:             $this->out(__d('cake_console', 'What is the association type?'));
686:             $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
687: 
688:             $this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\n" .
689:                 "Any spelling mistakes will cause errors."));
690:             $this->hr();
691: 
692:             $alias = $this->in(__d('cake_console', 'What is the alias for this association?'));
693:             $className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias);
694: 
695:             if ($assocType === 0) {
696:                 if (!empty($possibleKeys[$model->table])) {
697:                     $showKeys = $possibleKeys[$model->table];
698:                 } else {
699:                     $showKeys = null;
700:                 }
701:                 $suggestedForeignKey = $this->_modelKey($alias);
702:             } else {
703:                 $otherTable = Inflector::tableize($className);
704:                 if (in_array($otherTable, $this->_tables)) {
705:                     if ($assocType < 3) {
706:                         if (!empty($possibleKeys[$otherTable])) {
707:                             $showKeys = $possibleKeys[$otherTable];
708:                         } else {
709:                             $showKeys = null;
710:                         }
711:                     } else {
712:                         $showKeys = null;
713:                     }
714:                 } else {
715:                     $otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
716:                     $showKeys = $possibleKeys[$otherTable];
717:                 }
718:                 $suggestedForeignKey = $this->_modelKey($model->name);
719:             }
720:             if (!empty($showKeys)) {
721:                 $this->out(__d('cake_console', 'A helpful List of possible keys'));
722:                 $foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
723:                 $foreignKey = $showKeys[intval($foreignKey)];
724:             }
725:             if (!isset($foreignKey)) {
726:                 $foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
727:             }
728:             if ($assocType === 3) {
729:                 $associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
730:                 $joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
731:             }
732:             $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
733:             $count = count($associations[$assocs[$assocType]]);
734:             $i = ($count > 0) ? $count : 0;
735:             $associations[$assocs[$assocType]][$i]['alias'] = $alias;
736:             $associations[$assocs[$assocType]][$i]['className'] = $className;
737:             $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
738:             if ($assocType === 3) {
739:                 $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
740:                 $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
741:             }
742:             $wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y', 'n'), 'y');
743:         }
744:         return $associations;
745:     }
746: 
747: /**
748:  * Finds all possible keys to use on custom associations.
749:  *
750:  * @return array array of tables and possible keys
751:  */
752:     protected function _generatePossibleKeys() {
753:         $possible = array();
754:         foreach ($this->_tables as $otherTable) {
755:             $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
756:             $modelFieldsTemp = $tempOtherModel->schema(true);
757:             foreach ($modelFieldsTemp as $fieldName => $field) {
758:                 if ($field['type'] === 'integer' || $field['type'] === 'string') {
759:                     $possible[$otherTable][] = $fieldName;
760:                 }
761:             }
762:         }
763:         return $possible;
764:     }
765: 
766: /**
767:  * Assembles and writes a Model file.
768:  *
769:  * @param string|object $name Model name or object
770:  * @param array|boolean $data if array and $name is not an object assume bake data, otherwise boolean.
771:  * @return string
772:  */
773:     public function bake($name, $data = array()) {
774:         if (is_object($name)) {
775:             if (!$data) {
776:                 $data = array();
777:                 $data['associations'] = $this->doAssociations($name);
778:                 $data['validate'] = $this->doValidation($name);
779:             }
780:             $data['primaryKey'] = $name->primaryKey;
781:             $data['useTable'] = $name->table;
782:             $data['useDbConfig'] = $name->useDbConfig;
783:             $data['name'] = $name = $name->name;
784:         } else {
785:             $data['name'] = $name;
786:         }
787:         $defaults = array(
788:             'associations' => array(),
789:             'validate' => array(),
790:             'primaryKey' => 'id',
791:             'useTable' => null,
792:             'useDbConfig' => 'default',
793:             'displayField' => null
794:         );
795:         $data = array_merge($defaults, $data);
796: 
797:         $pluginPath = '';
798:         if ($this->plugin) {
799:             $pluginPath = $this->plugin . '.';
800:         }
801: 
802:         $this->Template->set($data);
803:         $this->Template->set(array(
804:             'plugin' => $this->plugin,
805:             'pluginPath' => $pluginPath
806:         ));
807:         $out = $this->Template->generate('classes', 'model');
808: 
809:         $path = $this->getPath();
810:         $filename = $path . $name . '.php';
811:         $this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
812:         $this->createFile($filename, $out);
813:         ClassRegistry::flush();
814:         return $out;
815:     }
816: 
817: /**
818:  * Assembles and writes a unit test file
819:  *
820:  * @param string $className Model class name
821:  * @return string
822:  */
823:     public function bakeTest($className) {
824:         $this->Test->interactive = $this->interactive;
825:         $this->Test->plugin = $this->plugin;
826:         $this->Test->connection = $this->connection;
827:         return $this->Test->bake('Model', $className);
828:     }
829: 
830: /**
831:  * outputs the a list of possible models or controllers from database
832:  *
833:  * @param string $useDbConfig Database configuration name
834:  * @return array
835:  */
836:     public function listAll($useDbConfig = null) {
837:         $this->_tables = (array)$this->getAllTables($useDbConfig);
838: 
839:         $this->_modelNames = array();
840:         $count = count($this->_tables);
841:         for ($i = 0; $i < $count; $i++) {
842:             $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
843:         }
844:         if ($this->interactive === true) {
845:             $this->out(__d('cake_console', 'Possible Models based on your current database:'));
846:             $len = strlen($count + 1);
847:             for ($i = 0; $i < $count; $i++) {
848:                 $this->out(sprintf("%${len}d. %s", $i + 1, $this->_modelNames[$i]));
849:             }
850:         }
851:         return $this->_tables;
852:     }
853: 
854: /**
855:  * Interact with the user to determine the table name of a particular model
856:  *
857:  * @param string $modelName Name of the model you want a table for.
858:  * @param string $useDbConfig Name of the database config you want to get tables from.
859:  * @return string Table name
860:  */
861:     public function getTable($modelName, $useDbConfig = null) {
862:         $useTable = Inflector::tableize($modelName);
863:         if (in_array($modelName, $this->_modelNames)) {
864:             $modelNames = array_flip($this->_modelNames);
865:             $useTable = $this->_tables[$modelNames[$modelName]];
866:         }
867: 
868:         if ($this->interactive === true) {
869:             if (!isset($useDbConfig)) {
870:                 $useDbConfig = $this->connection;
871:             }
872:             $db = ConnectionManager::getDataSource($useDbConfig);
873:             $fullTableName = $db->fullTableName($useTable, false);
874:             $tableIsGood = false;
875:             if (array_search($useTable, $this->_tables) === false) {
876:                 $this->out();
877:                 $this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
878:                 $tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y', 'n'), 'y');
879:             }
880:             if (strtolower($tableIsGood) === 'n') {
881:                 $useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
882:             }
883:         }
884:         return $useTable;
885:     }
886: 
887: /**
888:  * Get an Array of all the tables in the supplied connection
889:  * will halt the script if no tables are found.
890:  *
891:  * @param string $useDbConfig Connection name to scan.
892:  * @return array Array of tables in the database.
893:  */
894:     public function getAllTables($useDbConfig = null) {
895:         if (!isset($useDbConfig)) {
896:             $useDbConfig = $this->connection;
897:         }
898: 
899:         $tables = array();
900:         $db = ConnectionManager::getDataSource($useDbConfig);
901:         $db->cacheSources = false;
902:         $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
903:         if ($usePrefix) {
904:             foreach ($db->listSources() as $table) {
905:                 if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
906:                     $tables[] = substr($table, strlen($usePrefix));
907:                 }
908:             }
909:         } else {
910:             $tables = $db->listSources();
911:         }
912:         if (empty($tables)) {
913:             $this->err(__d('cake_console', 'Your database does not have any tables.'));
914:             return $this->_stop();
915:         }
916:         return $tables;
917:     }
918: 
919: /**
920:  * Forces the user to specify the model he wants to bake, and returns the selected model name.
921:  *
922:  * @param string $useDbConfig Database config name
923:  * @return string the model name
924:  */
925:     public function getName($useDbConfig = null) {
926:         $this->listAll($useDbConfig);
927: 
928:         $enteredModel = '';
929: 
930:         while (!$enteredModel) {
931:             $enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\n" .
932:                 "type in the name of another model, or 'q' to exit"), null, 'q');
933: 
934:             if ($enteredModel === 'q') {
935:                 $this->out(__d('cake_console', 'Exit'));
936:                 return $this->_stop();
937:             }
938: 
939:             if (!$enteredModel || intval($enteredModel) > count($this->_modelNames)) {
940:                 $this->err(__d('cake_console', "The model name you supplied was empty,\n" .
941:                     "or the number you selected was not an option. Please try again."));
942:                 $enteredModel = '';
943:             }
944:         }
945:         if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
946:             return $this->_modelNames[intval($enteredModel) - 1];
947:         }
948: 
949:         return $enteredModel;
950:     }
951: 
952: /**
953:  * get the option parser.
954:  *
955:  * @return void
956:  */
957:     public function getOptionParser() {
958:         $parser = parent::getOptionParser();
959:         return $parser->description(
960:                 __d('cake_console', 'Bake models.')
961:             )->addArgument('name', array(
962:                 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
963:             ))->addSubcommand('all', array(
964:                 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
965:             ))->addOption('plugin', array(
966:                 'short' => 'p',
967:                 'help' => __d('cake_console', 'Plugin to bake the model into.')
968:             ))->addOption('connection', array(
969:                 'short' => 'c',
970:                 'help' => __d('cake_console', 'The connection the model table is on.')
971:             ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
972:     }
973: 
974: /**
975:  * Interact with FixtureTask to automatically bake fixtures when baking models.
976:  *
977:  * @param string $className Name of class to bake fixture for
978:  * @param string $useTable Optional table name for fixture to use.
979:  * @return void
980:  * @see FixtureTask::bake
981:  */
982:     public function bakeFixture($className, $useTable = null) {
983:         $this->Fixture->interactive = $this->interactive;
984:         $this->Fixture->connection = $this->connection;
985:         $this->Fixture->plugin = $this->plugin;
986:         $this->Fixture->bake($className, $useTable);
987:     }
988: 
989: }
990: 
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