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' => 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: 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: $importOptions = $this->importOptions($model);
129: $this->bake($model, false, $importOptions);
130: }
131: }
132:
133: 134: 135: 136: 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: 155: 156: 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: 175: 176: 177: 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: 215: 216: 217: 218: 219: 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: 276: 277: 278: 279: 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: 299: 300: 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: 312: 313: 314: 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: 323: 324: 325: 326: 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: 391: 392: 393: 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: 416: 417: 418: 419: 420: 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: