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