1: <?php
  2:   3:   4:   5:   6:   7:   8:   9:  10:  11:  12:  13:  14:  15:  16: 
 17: 
 18: App::uses('AppShell', 'Console/Command');
 19: App::uses('BakeTask', 'Console/Command/Task');
 20: App::uses('Model', 'Model');
 21: 
 22:  23:  24:  25:  26: 
 27: class FixtureTask extends BakeTask {
 28: 
 29:  30:  31:  32:  33: 
 34:     public $tasks = array('DbConfig', 'Model', 'Template');
 35: 
 36:  37:  38:  39:  40: 
 41:     public $path = null;
 42: 
 43:  44:  45:  46:  47: 
 48:     protected $_Schema = null;
 49: 
 50:  51:  52:  53:  54:  55:  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:  64:  65:  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' => 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('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: 109: 110: 111: 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:             $this->bake($model);
129:         }
130:     }
131: 
132: 133: 134: 135: 136: 
137:     public function all() {
138:         $this->interactive = false;
139:         $this->Model->interactive = false;
140:         $tables = $this->Model->listAll($this->connection, false);
141: 
142:         foreach ($tables as $table) {
143:             $model = $this->_modelName($table);
144:             $importOptions = array();
145:             if (!empty($this->params['schema'])) {
146:                 $importOptions['schema'] = $model;
147:             }
148:             $this->bake($model, false, $importOptions);
149:         }
150:     }
151: 
152: 153: 154: 155: 156: 
157:     protected function _interactive() {
158:         $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
159:         $this->hr();
160:         $this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->getPath()));
161:         $this->hr();
162: 
163:         if (!isset($this->connection)) {
164:             $this->connection = $this->DbConfig->getConfig();
165:         }
166:         $modelName = $this->Model->getName($this->connection);
167:         $useTable = $this->Model->getTable($modelName, $this->connection);
168:         $importOptions = $this->importOptions($modelName);
169:         $this->bake($modelName, $useTable, $importOptions);
170:     }
171: 
172: 173: 174: 175: 176: 177: 
178:     public function importOptions($modelName) {
179:         $options = array();
180: 
181:         if (!empty($this->params['schema'])) {
182:             $options['schema'] = $modelName;
183:         } else {
184:             $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
185:             if ($doSchema === 'y') {
186:                 $options['schema'] = $modelName;
187:             }
188:         }
189:         if (!empty($this->params['records'])) {
190:             $doRecords = 'y';
191:         } else {
192:             $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
193:         }
194:         if ($doRecords === 'y') {
195:             $options['records'] = true;
196:         }
197:         if ($doRecords === 'n') {
198:             $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
199:             $fromTable = $this->in($prompt, array('y', 'n'), 'n');
200:             if (strtolower($fromTable) === 'y') {
201:                 $options['fromTable'] = true;
202:             }
203:         }
204:         return $options;
205:     }
206: 
207: 208: 209: 210: 211: 212: 213: 214: 
215:     public function bake($model, $useTable = false, $importOptions = array()) {
216:         App::uses('CakeSchema', 'Model');
217:         $table = $schema = $records = $import = $modelImport = null;
218:         $importBits = array();
219: 
220:         if (!$useTable) {
221:             $useTable = Inflector::tableize($model);
222:         } elseif ($useTable != Inflector::tableize($model)) {
223:             $table = $useTable;
224:         }
225: 
226:         if (!empty($importOptions)) {
227:             if (isset($importOptions['schema'])) {
228:                 $modelImport = true;
229:                 $importBits[] = "'model' => '{$importOptions['schema']}'";
230:             }
231:             if (isset($importOptions['records'])) {
232:                 $importBits[] = "'records' => true";
233:             }
234:             if ($this->connection !== 'default') {
235:                 $importBits[] .= "'connection' => '{$this->connection}'";
236:             }
237:             if (!empty($importBits)) {
238:                 $import = sprintf("array(%s)", implode(', ', $importBits));
239:             }
240:         }
241: 
242:         $this->_Schema = new CakeSchema();
243:         $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
244:         if (!isset($data['tables'][$useTable])) {
245:             $this->err("<warning>Warning:</warning> Could not find the '${useTable}' table for ${model}.");
246:             return;
247:         }
248: 
249:         $tableInfo = $data['tables'][$useTable];
250:         if ($modelImport === null) {
251:             $schema = $this->_generateSchema($tableInfo);
252:         }
253: 
254:         if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
255:             $recordCount = 1;
256:             if (isset($this->params['count'])) {
257:                 $recordCount = $this->params['count'];
258:             }
259:             $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
260:         }
261:         if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
262:             $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
263:         }
264:         $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
265:         return $out;
266:     }
267: 
268: 269: 270: 271: 272: 273: 274: 
275:     public function generateFixtureFile($model, $otherVars) {
276:         $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
277:         $vars = array_merge($defaults, $otherVars);
278: 
279:         $path = $this->getPath();
280:         $filename = Inflector::camelize($model) . 'Fixture.php';
281: 
282:         $this->Template->set('model', $model);
283:         $this->Template->set($vars);
284:         $content = $this->Template->generate('classes', 'fixture');
285: 
286:         $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
287:         $this->createFile($path . $filename, $content);
288:         return $content;
289:     }
290: 
291: 292: 293: 294: 295: 
296:     public function getPath() {
297:         $path = $this->path;
298:         if (isset($this->plugin)) {
299:             $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
300:         }
301:         return $path;
302:     }
303: 
304: 305: 306: 307: 308: 309: 
310:     protected function _generateSchema($tableInfo) {
311:         $schema = trim($this->_Schema->generateTable('f', $tableInfo), "\n");
312:         return substr($schema, 13, -1);
313:     }
314: 
315: 316: 317: 318: 319: 320: 321: 
322:     protected function _generateRecords($tableInfo, $recordCount = 1) {
323:         $records = array();
324:         for ($i = 0; $i < $recordCount; $i++) {
325:             $record = array();
326:             foreach ($tableInfo as $field => $fieldInfo) {
327:                 if (empty($fieldInfo['type'])) {
328:                     continue;
329:                 }
330:                 $insert = '';
331:                 switch ($fieldInfo['type']) {
332:                     case 'integer':
333:                     case 'float':
334:                         $insert = $i + 1;
335:                         break;
336:                     case 'string':
337:                     case 'binary':
338:                         $isPrimaryUuid = (
339:                             isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' &&
340:                             isset($fieldInfo['length']) && $fieldInfo['length'] == 36
341:                         );
342:                         if ($isPrimaryUuid) {
343:                             $insert = String::uuid();
344:                         } else {
345:                             $insert = "Lorem ipsum dolor sit amet";
346:                             if (!empty($fieldInfo['length'])) {
347:                                 $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
348:                             }
349:                         }
350:                         break;
351:                     case 'timestamp':
352:                         $insert = time();
353:                         break;
354:                     case 'datetime':
355:                         $insert = date('Y-m-d H:i:s');
356:                         break;
357:                     case 'date':
358:                         $insert = date('Y-m-d');
359:                         break;
360:                     case 'time':
361:                         $insert = date('H:i:s');
362:                         break;
363:                     case 'boolean':
364:                         $insert = 1;
365:                         break;
366:                     case 'text':
367:                         $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
368:                         $insert .= " Convallis morbi fringilla gravida,";
369:                         $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
370:                         $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
371:                         $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
372:                         $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
373:                         $insert .= " duis vestibulum nunc mattis convallis.";
374:                         break;
375:                 }
376:                 $record[$field] = $insert;
377:             }
378:             $records[] = $record;
379:         }
380:         return $records;
381:     }
382: 
383: 384: 385: 386: 387: 388: 
389:     protected function _makeRecordString($records) {
390:         $out = "array(\n";
391:         foreach ($records as $record) {
392:             $values = array();
393:             foreach ($record as $field => $value) {
394:                 $val = var_export($value, true);
395:                 if ($val === 'NULL') {
396:                     $val = 'null';
397:                 }
398:                 $values[] = "\t\t\t'$field' => $val";
399:             }
400:             $out .= "\t\tarray(\n";
401:             $out .= implode(",\n", $values);
402:             $out .= "\n\t\t),\n";
403:         }
404:         $out .= "\t)";
405:         return $out;
406:     }
407: 
408: 409: 410: 411: 412: 413: 414: 415: 
416:     protected function _getRecordsFromTable($modelName, $useTable = null) {
417:         if ($this->interactive) {
418:             $condition = null;
419:             $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
420:             while (!$condition) {
421:                 $condition = $this->in($prompt, null, 'WHERE 1=1');
422:             }
423:             $prompt = __d('cake_console', "How many records do you want to import?");
424:             $recordCount = $this->in($prompt, null, 10);
425:         } else {
426:             $condition = 'WHERE 1=1';
427:             $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
428:         }
429:         $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
430:         $records = $modelObject->find('all', array(
431:             'conditions' => $condition,
432:             'recursive' => -1,
433:             'limit' => $recordCount
434:         ));
435: 
436:         $schema = $modelObject->schema(true);
437:         $out = array();
438:         foreach ($records as $record) {
439:             $row = array();
440:             foreach ($record[$modelObject->alias] as $field => $value) {
441:                 if ($schema[$field]['type'] === 'boolean') {
442:                     $value = (int)(bool)$value;
443:                 }
444:                 $row[$field] = $value;
445:             }
446:             $out[] = $row;
447:         }
448:         return $out;
449:     }
450: 
451: }
452: