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 'tinyinteger':
339: case 'smallinteger':
340: case 'biginteger':
341: case 'integer':
342: case 'float':
343: $insert = $i + 1;
344: break;
345: case 'string':
346: case 'binary':
347: $isPrimaryUuid = (
348: isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' &&
349: isset($fieldInfo['length']) && $fieldInfo['length'] == 36
350: );
351: if ($isPrimaryUuid) {
352: $insert = CakeText::uuid();
353: } else {
354: $insert = "Lorem ipsum dolor sit amet";
355: if (!empty($fieldInfo['length'])) {
356: $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
357: }
358: }
359: break;
360: case 'timestamp':
361: $insert = time();
362: break;
363: case 'datetime':
364: $insert = date('Y-m-d H:i:s');
365: break;
366: case 'date':
367: $insert = date('Y-m-d');
368: break;
369: case 'time':
370: $insert = date('H:i:s');
371: break;
372: case 'boolean':
373: $insert = 1;
374: break;
375: case 'text':
376: $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
377: $insert .= " Convallis morbi fringilla gravida,";
378: $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
379: $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
380: $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
381: $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
382: $insert .= " duis vestibulum nunc mattis convallis.";
383: break;
384: }
385: $record[$field] = $insert;
386: }
387: $records[] = $record;
388: }
389: return $records;
390: }
391:
392: 393: 394: 395: 396: 397:
398: protected function _makeRecordString($records) {
399: $out = "array(\n";
400: foreach ($records as $record) {
401: $values = array();
402: foreach ($record as $field => $value) {
403: $val = var_export($value, true);
404: if ($val === 'NULL') {
405: $val = 'null';
406: }
407: $values[] = "\t\t\t'$field' => $val";
408: }
409: $out .= "\t\tarray(\n";
410: $out .= implode(",\n", $values);
411: $out .= "\n\t\t),\n";
412: }
413: $out .= "\t)";
414: return $out;
415: }
416:
417: 418: 419: 420: 421: 422: 423: 424:
425: protected function _getRecordsFromTable($modelName, $useTable = null) {
426: $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
427: if ($this->interactive) {
428: $condition = null;
429: $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
430: while (!$condition) {
431: $condition = $this->in($prompt, null, 'WHERE 1=1');
432: }
433:
434: $recordsFound = $modelObject->find('count', array(
435: 'conditions' => $condition,
436: 'recursive' => -1,
437: ));
438:
439: $prompt = __d('cake_console', "How many records do you want to import?");
440: $recordCount = $this->in($prompt, null, ($recordsFound < 10 ) ? $recordsFound : 10);
441: } else {
442: $condition = 'WHERE 1=1';
443: $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
444: }
445:
446: $records = $modelObject->find('all', array(
447: 'conditions' => $condition,
448: 'recursive' => -1,
449: 'limit' => $recordCount
450: ));
451:
452: $schema = $modelObject->schema(true);
453: $out = array();
454: foreach ($records as $record) {
455: $row = array();
456: foreach ($record[$modelObject->alias] as $field => $value) {
457: if ($schema[$field]['type'] === 'boolean') {
458: $value = (int)(bool)$value;
459: }
460: $row[$field] = $value;
461: }
462: $out[] = $row;
463: }
464: return $out;
465: }
466:
467: }
468: