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