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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.9
      • 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
  • None

Classes

  • BakeTask
  • CommandTask
  • ControllerTask
  • DbConfigTask
  • ExtractTask
  • FixtureTask
  • ModelTask
  • PluginTask
  • ProjectTask
  • TemplateTask
  • TestTask
  • ViewTask
  1: <?php
  2: /**
  3:  * The FixtureTask handles creating and updating fixture files.
  4:  *
  5:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7:  *
  8:  * Licensed under The MIT License
  9:  * For full copyright and license information, please see the LICENSE.txt
 10:  * Redistributions of files must retain the above copyright notice.
 11:  *
 12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 13:  * @link          http://cakephp.org CakePHP(tm) Project
 14:  * @since         CakePHP(tm) v 1.3
 15:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 16:  */
 17: 
 18: App::uses('AppShell', 'Console/Command');
 19: App::uses('BakeTask', 'Console/Command/Task');
 20: App::uses('Model', 'Model');
 21: 
 22: /**
 23:  * Task class for creating and updating fixtures files.
 24:  *
 25:  * @package       Cake.Console.Command.Task
 26:  */
 27: class FixtureTask extends BakeTask {
 28: 
 29: /**
 30:  * Tasks to be loaded by this Task
 31:  *
 32:  * @var array
 33:  */
 34:     public $tasks = array('DbConfig', 'Model', 'Template');
 35: 
 36: /**
 37:  * path to fixtures directory
 38:  *
 39:  * @var string
 40:  */
 41:     public $path = null;
 42: 
 43: /**
 44:  * Schema instance
 45:  *
 46:  * @var CakeSchema
 47:  */
 48:     protected $_Schema = null;
 49: 
 50: /**
 51:  * Override initialize
 52:  *
 53:  * @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
 54:  * @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
 55:  * @param ConsoleInput $stdin A ConsoleInput object for stdin.
 56:  */
 57:     public function __construct($stdout = null, $stderr = null, $stdin = null) {
 58:         parent::__construct($stdout, $stderr, $stdin);
 59:         $this->path = APP . 'Test' . DS . 'Fixture' . DS;
 60:     }
 61: 
 62: /**
 63:  * Gets the option parser instance and configures it.
 64:  *
 65:  * @return ConsoleOptionParser
 66:  */
 67:     public function getOptionParser() {
 68:         $parser = parent::getOptionParser();
 69: 
 70:         $parser->description(
 71:             __d('cake_console', 'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.')
 72:         )->addArgument('name', array(
 73:             'help' => __d('cake_console', 'Name of the fixture to bake. Can use Plugin.name to bake plugin fixtures.')
 74:         ))->addOption('count', array(
 75:             'help' => __d('cake_console', 'When using generated data, the number of records to include in the fixture(s).'),
 76:             'short' => 'n',
 77:             'default' => 1
 78:         ))->addOption('connection', array(
 79:             'help' => __d('cake_console', 'Which database configuration to use for baking.'),
 80:             'short' => 'c',
 81:             'default' => 'default'
 82:         ))->addOption('plugin', array(
 83:             'help' => __d('cake_console', 'CamelCased name of the plugin to bake fixtures for.'),
 84:             'short' => 'p'
 85:         ))->addOption('schema', array(
 86:             'help' => __d('cake_console', 'Importing schema for fixtures rather than hardcoding it.'),
 87:             'short' => 's',
 88:             'boolean' => true
 89:         ))->addOption('theme', array(
 90:             'short' => 't',
 91:             'help' => __d('cake_console', 'Theme to use when baking code.')
 92:         ))->addOption('force', array(
 93:             'short' => 'f',
 94:             'help' => __d('cake_console', 'Force overwriting existing files without prompting.')
 95:         ))->addOption('records', array(
 96:             'help' => __d('cake_console', 'Used with --count and <name>/all commands to pull [n] records from the live tables, ' .
 97:                 'where [n] is either --count or the default of 10.'),
 98:             'short' => 'r',
 99:             'boolean' => true
100:         ))->epilog(
101:             __d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.')
102:         );
103: 
104:         return $parser;
105:     }
106: 
107: /**
108:  * Execution method always used for tasks
109:  * Handles dispatching to interactive, named, or all processes.
110:  *
111:  * @return void
112:  */
113:     public function execute() {
114:         parent::execute();
115:         if (empty($this->args)) {
116:             $this->_interactive();
117:         }
118: 
119:         if (isset($this->args[0])) {
120:             $this->interactive = false;
121:             if (!isset($this->connection)) {
122:                 $this->connection = 'default';
123:             }
124:             if (strtolower($this->args[0]) === 'all') {
125:                 return $this->all();
126:             }
127:             $model = $this->_modelName($this->args[0]);
128:             $importOptions = $this->importOptions($model);
129:             $this->bake($model, false, $importOptions);
130:         }
131:     }
132: 
133: /**
134:  * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
135:  *
136:  * @return void
137:  */
138:     public function all() {
139:         $this->interactive = false;
140:         $this->Model->interactive = false;
141:         $tables = $this->Model->listAll($this->connection, false);
142: 
143:         foreach ($tables as $table) {
144:             $model = $this->_modelName($table);
145:             $importOptions = array();
146:             if (!empty($this->params['schema'])) {
147:                 $importOptions['schema'] = $model;
148:             }
149:             $this->bake($model, false, $importOptions);
150:         }
151:     }
152: 
153: /**
154:  * Interactive baking function
155:  *
156:  * @return void
157:  */
158:     protected function _interactive() {
159:         $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
160:         $this->hr();
161:         $this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->getPath()));
162:         $this->hr();
163: 
164:         if (!isset($this->connection)) {
165:             $this->connection = $this->DbConfig->getConfig();
166:         }
167:         $modelName = $this->Model->getName($this->connection);
168:         $useTable = $this->Model->getTable($modelName, $this->connection);
169:         $importOptions = $this->importOptions($modelName);
170:         $this->bake($modelName, $useTable, $importOptions);
171:     }
172: 
173: /**
174:  * Interacts with the User to setup an array of import options. For a fixture.
175:  *
176:  * @param string $modelName Name of model you are dealing with.
177:  * @return array Array of import options.
178:  */
179:     public function importOptions($modelName) {
180:         $options = array();
181:         $plugin = '';
182:         if (isset($this->params['plugin'])) {
183:             $plugin = $this->params['plugin'] . '.';
184:         }
185: 
186:         if (!empty($this->params['schema'])) {
187:             $options['schema'] = $plugin . $modelName;
188:         } elseif ($this->interactive) {
189:             $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
190:             if ($doSchema === 'y') {
191:                 $options['schema'] = $modelName;
192:             }
193:         }
194: 
195:         if (!empty($this->params['records'])) {
196:             $options['fromTable'] = true;
197:         } elseif ($this->interactive) {
198:             $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
199:             if ($doRecords === 'y') {
200:                 $options['records'] = true;
201:             }
202:         }
203:         if (!isset($options['records']) && $this->interactive) {
204:             $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
205:             $fromTable = $this->in($prompt, array('y', 'n'), 'n');
206:             if (strtolower($fromTable) === 'y') {
207:                 $options['fromTable'] = true;
208:             }
209:         }
210:         return $options;
211:     }
212: 
213: /**
214:  * Assembles and writes a Fixture file
215:  *
216:  * @param string $model Name of model to bake.
217:  * @param string $useTable Name of table to use.
218:  * @param array $importOptions Options for public $import
219:  * @return string|null Baked fixture content, otherwise null.
220:  */
221:     public function bake($model, $useTable = false, $importOptions = array()) {
222:         App::uses('CakeSchema', 'Model');
223:         $table = $schema = $records = $import = $modelImport = null;
224:         $importBits = array();
225: 
226:         if (!$useTable) {
227:             $useTable = Inflector::tableize($model);
228:         } elseif ($useTable != Inflector::tableize($model)) {
229:             $table = $useTable;
230:         }
231: 
232:         if (!empty($importOptions)) {
233:             if (isset($importOptions['schema'])) {
234:                 $modelImport = true;
235:                 $importBits[] = "'model' => '{$importOptions['schema']}'";
236:             }
237:             if (isset($importOptions['records'])) {
238:                 $importBits[] = "'records' => true";
239:             }
240:             if ($this->connection !== 'default') {
241:                 $importBits[] .= "'connection' => '{$this->connection}'";
242:             }
243:             if (!empty($importBits)) {
244:                 $import = sprintf("array(%s)", implode(', ', $importBits));
245:             }
246:         }
247: 
248:         $this->_Schema = new CakeSchema();
249:         $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
250:         if (!isset($data['tables'][$useTable])) {
251:             $this->err("<warning>Warning:</warning> Could not find the '${useTable}' table for ${model}.");
252:             return null;
253:         }
254: 
255:         $tableInfo = $data['tables'][$useTable];
256:         if ($modelImport === null) {
257:             $schema = $this->_generateSchema($tableInfo);
258:         }
259: 
260:         if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
261:             $recordCount = 1;
262:             if (isset($this->params['count'])) {
263:                 $recordCount = $this->params['count'];
264:             }
265:             $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
266:         }
267:         if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
268:             $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
269:         }
270:         $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
271:         return $out;
272:     }
273: 
274: /**
275:  * Generate the fixture file, and write to disk
276:  *
277:  * @param string $model name of the model being generated
278:  * @param string $otherVars Contents of the fixture file.
279:  * @return string Content saved into fixture file.
280:  */
281:     public function generateFixtureFile($model, $otherVars) {
282:         $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
283:         $vars = array_merge($defaults, $otherVars);
284: 
285:         $path = $this->getPath();
286:         $filename = Inflector::camelize($model) . 'Fixture.php';
287: 
288:         $this->Template->set('model', $model);
289:         $this->Template->set($vars);
290:         $content = $this->Template->generate('classes', 'fixture');
291: 
292:         $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
293:         $this->createFile($path . $filename, $content);
294:         return $content;
295:     }
296: 
297: /**
298:  * Get the path to the fixtures.
299:  *
300:  * @return string Path for the fixtures
301:  */
302:     public function getPath() {
303:         $path = $this->path;
304:         if (isset($this->plugin)) {
305:             $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
306:         }
307:         return $path;
308:     }
309: 
310: /**
311:  * Generates a string representation of a schema.
312:  *
313:  * @param array $tableInfo Table schema array
314:  * @return string fields definitions
315:  */
316:     protected function _generateSchema($tableInfo) {
317:         $schema = trim($this->_Schema->generateTable('f', $tableInfo), "\n");
318:         return substr($schema, 13, -1);
319:     }
320: 
321: /**
322:  * Generate String representation of Records
323:  *
324:  * @param array $tableInfo Table schema array
325:  * @param int $recordCount The number of records to generate.
326:  * @return array Array of records to use in the fixture.
327:  */
328:     protected function _generateRecords($tableInfo, $recordCount = 1) {
329:         $records = array();
330:         for ($i = 0; $i < $recordCount; $i++) {
331:             $record = array();
332:             foreach ($tableInfo as $field => $fieldInfo) {
333:                 if (empty($fieldInfo['type'])) {
334:                     continue;
335:                 }
336:                 $insert = '';
337:                 switch ($fieldInfo['type']) {
338:                     case 'integer':
339:                     case 'float':
340:                         $insert = $i + 1;
341:                         break;
342:                     case 'string':
343:                     case 'binary':
344:                         $isPrimaryUuid = (
345:                             isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' &&
346:                             isset($fieldInfo['length']) && $fieldInfo['length'] == 36
347:                         );
348:                         if ($isPrimaryUuid) {
349:                             $insert = CakeText::uuid();
350:                         } else {
351:                             $insert = "Lorem ipsum dolor sit amet";
352:                             if (!empty($fieldInfo['length'])) {
353:                                 $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
354:                             }
355:                         }
356:                         break;
357:                     case 'timestamp':
358:                         $insert = time();
359:                         break;
360:                     case 'datetime':
361:                         $insert = date('Y-m-d H:i:s');
362:                         break;
363:                     case 'date':
364:                         $insert = date('Y-m-d');
365:                         break;
366:                     case 'time':
367:                         $insert = date('H:i:s');
368:                         break;
369:                     case 'boolean':
370:                         $insert = 1;
371:                         break;
372:                     case 'text':
373:                         $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
374:                         $insert .= " Convallis morbi fringilla gravida,";
375:                         $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
376:                         $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
377:                         $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
378:                         $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
379:                         $insert .= " duis vestibulum nunc mattis convallis.";
380:                         break;
381:                 }
382:                 $record[$field] = $insert;
383:             }
384:             $records[] = $record;
385:         }
386:         return $records;
387:     }
388: 
389: /**
390:  * Convert a $records array into a string.
391:  *
392:  * @param array $records Array of records to be converted to string
393:  * @return string A string value of the $records array.
394:  */
395:     protected function _makeRecordString($records) {
396:         $out = "array(\n";
397:         foreach ($records as $record) {
398:             $values = array();
399:             foreach ($record as $field => $value) {
400:                 $val = var_export($value, true);
401:                 if ($val === 'NULL') {
402:                     $val = 'null';
403:                 }
404:                 $values[] = "\t\t\t'$field' => $val";
405:             }
406:             $out .= "\t\tarray(\n";
407:             $out .= implode(",\n", $values);
408:             $out .= "\n\t\t),\n";
409:         }
410:         $out .= "\t)";
411:         return $out;
412:     }
413: 
414: /**
415:  * Interact with the user to get a custom SQL condition and use that to extract data
416:  * to build a fixture.
417:  *
418:  * @param string $modelName name of the model to take records from.
419:  * @param string $useTable Name of table to use.
420:  * @return array Array of records.
421:  */
422:     protected function _getRecordsFromTable($modelName, $useTable = null) {
423:         $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
424:         if ($this->interactive) {
425:             $condition = null;
426:             $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
427:             while (!$condition) {
428:                 $condition = $this->in($prompt, null, 'WHERE 1=1');
429:             }
430: 
431:             $recordsFound = $modelObject->find('count', array(
432:                 'conditions' => $condition,
433:                 'recursive' => -1,
434:             ));
435: 
436:             $prompt = __d('cake_console', "How many records do you want to import?");
437:             $recordCount = $this->in($prompt, null, ($recordsFound < 10 ) ? $recordsFound : 10);
438:         } else {
439:             $condition = 'WHERE 1=1';
440:             $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
441:         }
442: 
443:         $records = $modelObject->find('all', array(
444:             'conditions' => $condition,
445:             'recursive' => -1,
446:             'limit' => $recordCount
447:         ));
448: 
449:         $schema = $modelObject->schema(true);
450:         $out = array();
451:         foreach ($records as $record) {
452:             $row = array();
453:             foreach ($record[$modelObject->alias] as $field => $value) {
454:                 if ($schema[$field]['type'] === 'boolean') {
455:                     $value = (int)(bool)$value;
456:                 }
457:                 $row[$field] = $value;
458:             }
459:             $out[] = $row;
460:         }
461:         return $out;
462:     }
463: 
464: }
465: 
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