1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18:
19:
20: App::uses('AppShell', 'Console/Command');
21: App::uses('BakeTask', 'Console/Command/Task');
22: App::uses('Model', 'Model');
23:
24: 25: 26: 27: 28:
29: class FixtureTask extends BakeTask {
30:
31: 32: 33: 34: 35:
36: public $tasks = array('DbConfig', 'Model', 'Template');
37:
38: 39: 40: 41: 42:
43: public $path = null;
44:
45: 46: 47: 48: 49:
50: protected $_Schema = null;
51:
52: 53: 54: 55: 56: 57: 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: 66: 67: 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: 95: 96: 97: 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: 120: 121: 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: 135: 136: 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: 155: 156: 157: 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: 181: 182: 183: 184: 185: 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: 242: 243: 244: 245: 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: 265: 266: 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: 278: 279: 280: 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: 289: 290: 291: 292: 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: 357: 358: 359: 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: 382: 383: 384: 385: 386: 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: