統計
| ブランチ: | リビジョン:

pictcode / lib / Cake / Console / Command / Task / FixtureTask.php @ 0b1b8047

履歴 | 表示 | アノテート | ダウンロード (13.573 KB)

1
<?php
2
/**
3
 * The FixtureTask handles creating and updating fixture files.
4
 *
5
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
6
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
7
 *
8
 * Licensed under The MIT License
9
 * For full copyright and license information, please see the LICENSE.txt
10
 * Redistributions of files must retain the above copyright notice.
11
 *
12
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
13
 * @link          http://cakephp.org CakePHP(tm) Project
14
 * @since         CakePHP(tm) v 1.3
15
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
16
 */
17

    
18
App::uses('AppShell', 'Console/Command');
19
App::uses('BakeTask', 'Console/Command/Task');
20
App::uses('Model', 'Model');
21

    
22
/**
23
 * Task class for creating and updating fixtures files.
24
 *
25
 * @package       Cake.Console.Command.Task
26
 */
27
class FixtureTask extends BakeTask {
28

    
29
/**
30
 * Tasks to be loaded by this Task
31
 *
32
 * @var array
33
 */
34
        public $tasks = array('DbConfig', 'Model', 'Template');
35

    
36
/**
37
 * path to fixtures directory
38
 *
39
 * @var string
40
 */
41
        public $path = null;
42

    
43
/**
44
 * Schema instance
45
 *
46
 * @var CakeSchema
47
 */
48
        protected $_Schema = null;
49

    
50
/**
51
 * Override initialize
52
 *
53
 * @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
54
 * @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
55
 * @param ConsoleInput $stdin A ConsoleInput object for stdin.
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
 * Gets the option parser instance and configures it.
64
 *
65
 * @return ConsoleOptionParser
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
 * Execution method always used for tasks
109
 * Handles dispatching to interactive, named, or all processes.
110
 *
111
 * @return void
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
                        $this->bake($model);
129
                }
130
        }
131

    
132
/**
133
 * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
134
 *
135
 * @return void
136
 */
137
        public function all() {
138
                $this->interactive = false;
139
                $this->Model->interactive = false;
140
                $tables = $this->Model->listAll($this->connection, false);
141

    
142
                foreach ($tables as $table) {
143
                        $model = $this->_modelName($table);
144
                        $importOptions = array();
145
                        if (!empty($this->params['schema'])) {
146
                                $importOptions['schema'] = $model;
147
                        }
148
                        $this->bake($model, false, $importOptions);
149
                }
150
        }
151

    
152
/**
153
 * Interactive baking function
154
 *
155
 * @return void
156
 */
157
        protected function _interactive() {
158
                $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
159
                $this->hr();
160
                $this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->getPath()));
161
                $this->hr();
162

    
163
                if (!isset($this->connection)) {
164
                        $this->connection = $this->DbConfig->getConfig();
165
                }
166
                $modelName = $this->Model->getName($this->connection);
167
                $useTable = $this->Model->getTable($modelName, $this->connection);
168
                $importOptions = $this->importOptions($modelName);
169
                $this->bake($modelName, $useTable, $importOptions);
170
        }
171

    
172
/**
173
 * Interacts with the User to setup an array of import options. For a fixture.
174
 *
175
 * @param string $modelName Name of model you are dealing with.
176
 * @return array Array of import options.
177
 */
178
        public function importOptions($modelName) {
179
                $options = array();
180

    
181
                if (!empty($this->params['schema'])) {
182
                        $options['schema'] = $modelName;
183
                } else {
184
                        $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
185
                        if ($doSchema === 'y') {
186
                                $options['schema'] = $modelName;
187
                        }
188
                }
189
                if (!empty($this->params['records'])) {
190
                        $doRecords = 'y';
191
                } else {
192
                        $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
193
                }
194
                if ($doRecords === 'y') {
195
                        $options['records'] = true;
196
                }
197
                if ($doRecords === 'n') {
198
                        $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
199
                        $fromTable = $this->in($prompt, array('y', 'n'), 'n');
200
                        if (strtolower($fromTable) === 'y') {
201
                                $options['fromTable'] = true;
202
                        }
203
                }
204
                return $options;
205
        }
206

    
207
/**
208
 * Assembles and writes a Fixture file
209
 *
210
 * @param string $model Name of model to bake.
211
 * @param string $useTable Name of table to use.
212
 * @param array $importOptions Options for public $import
213
 * @return string|null Baked fixture content, otherwise null.
214
 */
215
        public function bake($model, $useTable = false, $importOptions = array()) {
216
                App::uses('CakeSchema', 'Model');
217
                $table = $schema = $records = $import = $modelImport = null;
218
                $importBits = array();
219

    
220
                if (!$useTable) {
221
                        $useTable = Inflector::tableize($model);
222
                } elseif ($useTable != Inflector::tableize($model)) {
223
                        $table = $useTable;
224
                }
225

    
226
                if (!empty($importOptions)) {
227
                        if (isset($importOptions['schema'])) {
228
                                $modelImport = true;
229
                                $importBits[] = "'model' => '{$importOptions['schema']}'";
230
                        }
231
                        if (isset($importOptions['records'])) {
232
                                $importBits[] = "'records' => true";
233
                        }
234
                        if ($this->connection !== 'default') {
235
                                $importBits[] .= "'connection' => '{$this->connection}'";
236
                        }
237
                        if (!empty($importBits)) {
238
                                $import = sprintf("array(%s)", implode(', ', $importBits));
239
                        }
240
                }
241

    
242
                $this->_Schema = new CakeSchema();
243
                $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
244
                if (!isset($data['tables'][$useTable])) {
245
                        $this->err("<warning>Warning:</warning> Could not find the '${useTable}' table for ${model}.");
246
                        return null;
247
                }
248

    
249
                $tableInfo = $data['tables'][$useTable];
250
                if ($modelImport === null) {
251
                        $schema = $this->_generateSchema($tableInfo);
252
                }
253

    
254
                if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
255
                        $recordCount = 1;
256
                        if (isset($this->params['count'])) {
257
                                $recordCount = $this->params['count'];
258
                        }
259
                        $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
260
                }
261
                if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
262
                        $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
263
                }
264
                $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
265
                return $out;
266
        }
267

    
268
/**
269
 * Generate the fixture file, and write to disk
270
 *
271
 * @param string $model name of the model being generated
272
 * @param string $otherVars Contents of the fixture file.
273
 * @return string Content saved into fixture file.
274
 */
275
        public function generateFixtureFile($model, $otherVars) {
276
                $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
277
                $vars = array_merge($defaults, $otherVars);
278

    
279
                $path = $this->getPath();
280
                $filename = Inflector::camelize($model) . 'Fixture.php';
281

    
282
                $this->Template->set('model', $model);
283
                $this->Template->set($vars);
284
                $content = $this->Template->generate('classes', 'fixture');
285

    
286
                $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
287
                $this->createFile($path . $filename, $content);
288
                return $content;
289
        }
290

    
291
/**
292
 * Get the path to the fixtures.
293
 *
294
 * @return string Path for the fixtures
295
 */
296
        public function getPath() {
297
                $path = $this->path;
298
                if (isset($this->plugin)) {
299
                        $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
300
                }
301
                return $path;
302
        }
303

    
304
/**
305
 * Generates a string representation of a schema.
306
 *
307
 * @param array $tableInfo Table schema array
308
 * @return string fields definitions
309
 */
310
        protected function _generateSchema($tableInfo) {
311
                $schema = trim($this->_Schema->generateTable('f', $tableInfo), "\n");
312
                return substr($schema, 13, -1);
313
        }
314

    
315
/**
316
 * Generate String representation of Records
317
 *
318
 * @param array $tableInfo Table schema array
319
 * @param int $recordCount The number of records to generate.
320
 * @return array Array of records to use in the fixture.
321
 */
322
        protected function _generateRecords($tableInfo, $recordCount = 1) {
323
                $records = array();
324
                for ($i = 0; $i < $recordCount; $i++) {
325
                        $record = array();
326
                        foreach ($tableInfo as $field => $fieldInfo) {
327
                                if (empty($fieldInfo['type'])) {
328
                                        continue;
329
                                }
330
                                $insert = '';
331
                                switch ($fieldInfo['type']) {
332
                                        case 'integer':
333
                                        case 'float':
334
                                                $insert = $i + 1;
335
                                                break;
336
                                        case 'string':
337
                                        case 'binary':
338
                                                $isPrimaryUuid = (
339
                                                        isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' &&
340
                                                        isset($fieldInfo['length']) && $fieldInfo['length'] == 36
341
                                                );
342
                                                if ($isPrimaryUuid) {
343
                                                        $insert = CakeText::uuid();
344
                                                } else {
345
                                                        $insert = "Lorem ipsum dolor sit amet";
346
                                                        if (!empty($fieldInfo['length'])) {
347
                                                                $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
348
                                                        }
349
                                                }
350
                                                break;
351
                                        case 'timestamp':
352
                                                $insert = time();
353
                                                break;
354
                                        case 'datetime':
355
                                                $insert = date('Y-m-d H:i:s');
356
                                                break;
357
                                        case 'date':
358
                                                $insert = date('Y-m-d');
359
                                                break;
360
                                        case 'time':
361
                                                $insert = date('H:i:s');
362
                                                break;
363
                                        case 'boolean':
364
                                                $insert = 1;
365
                                                break;
366
                                        case 'text':
367
                                                $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
368
                                                $insert .= " Convallis morbi fringilla gravida,";
369
                                                $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
370
                                                $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
371
                                                $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
372
                                                $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
373
                                                $insert .= " duis vestibulum nunc mattis convallis.";
374
                                                break;
375
                                }
376
                                $record[$field] = $insert;
377
                        }
378
                        $records[] = $record;
379
                }
380
                return $records;
381
        }
382

    
383
/**
384
 * Convert a $records array into a string.
385
 *
386
 * @param array $records Array of records to be converted to string
387
 * @return string A string value of the $records array.
388
 */
389
        protected function _makeRecordString($records) {
390
                $out = "array(\n";
391
                foreach ($records as $record) {
392
                        $values = array();
393
                        foreach ($record as $field => $value) {
394
                                $val = var_export($value, true);
395
                                if ($val === 'NULL') {
396
                                        $val = 'null';
397
                                }
398
                                $values[] = "\t\t\t'$field' => $val";
399
                        }
400
                        $out .= "\t\tarray(\n";
401
                        $out .= implode(",\n", $values);
402
                        $out .= "\n\t\t),\n";
403
                }
404
                $out .= "\t)";
405
                return $out;
406
        }
407

    
408
/**
409
 * Interact with the user to get a custom SQL condition and use that to extract data
410
 * to build a fixture.
411
 *
412
 * @param string $modelName name of the model to take records from.
413
 * @param string $useTable Name of table to use.
414
 * @return array Array of records.
415
 */
416
        protected function _getRecordsFromTable($modelName, $useTable = null) {
417
                $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
418
                if ($this->interactive) {
419
                        $condition = null;
420
                        $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
421
                        while (!$condition) {
422
                                $condition = $this->in($prompt, null, 'WHERE 1=1');
423
                        }
424

    
425
                        $recordsFound = $modelObject->find('count', array(
426
                                'conditions' => $condition,
427
                                'recursive' => -1,
428
                        ));
429

    
430
                        $prompt = __d('cake_console', "How many records do you want to import?");
431
                        $recordCount = $this->in($prompt, null, ($recordsFound < 10 ) ? $recordsFound : 10);
432
                } else {
433
                        $condition = 'WHERE 1=1';
434
                        $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
435
                }
436

    
437
                $records = $modelObject->find('all', array(
438
                        'conditions' => $condition,
439
                        'recursive' => -1,
440
                        'limit' => $recordCount
441
                ));
442

    
443
                $schema = $modelObject->schema(true);
444
                $out = array();
445
                foreach ($records as $record) {
446
                        $row = array();
447
                        foreach ($record[$modelObject->alias] as $field => $value) {
448
                                if ($schema[$field]['type'] === 'boolean') {
449
                                        $value = (int)(bool)$value;
450
                                }
451
                                $row[$field] = $value;
452
                        }
453
                        $out[] = $row;
454
                }
455
                return $out;
456
        }
457

    
458
}