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