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

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