/
TestFixture.php
469 lines (407 loc) · 12.2 KB
/
TestFixture.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @since 1.2.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\TestSuite\Fixture;
use Cake\Core\Exception\Exception as CakeException;
use Cake\Database\Schema\TableSchema;
use Cake\Database\Schema\TableSchemaAwareInterface;
use Cake\Database\Schema\TableSchemaInterface as DatabaseTableSchemaInterface;
use Cake\Datasource\ConnectionInterface;
use Cake\Datasource\ConnectionManager;
use Cake\Datasource\FixtureInterface;
use Cake\Datasource\TableSchemaInterface;
use Cake\Log\Log;
use Cake\ORM\TableRegistry;
use Cake\Utility\Inflector;
use Exception;
/**
* Cake TestFixture is responsible for building and destroying tables to be used
* during testing.
*/
class TestFixture implements FixtureInterface, TableSchemaInterface, TableSchemaAwareInterface
{
/**
* Fixture Datasource
*
* @var string
*/
public $connection = 'test';
/**
* Full Table Name
*
* @var string
*/
public $table;
/**
* Fields / Schema for the fixture.
*
* This array should be compatible with Cake\Database\Schema\Schema.
* The `_constraints`, `_options` and `_indexes` keys are reserved for defining
* constraints, options and indexes respectively.
*
* @var array
*/
public $fields = [];
/**
* Configuration for importing fixture schema
*
* Accepts a `connection` and `model` or `table` key, to define
* which table and which connection contain the schema to be
* imported.
*
* @var array|null
*/
public $import;
/**
* Fixture records to be inserted.
*
* @var array
*/
public $records = [];
/**
* The schema for this fixture.
*
* @var \Cake\Database\Schema\TableSchema|\Cake\Database\Schema\TableSchemaInterface
*/
protected $_schema;
/**
* Fixture constraints to be created.
*
* @var array
*/
protected $_constraints = [];
/**
* Instantiate the fixture.
*
* @throws \Cake\Core\Exception\Exception on invalid datasource usage.
*/
public function __construct()
{
if (!empty($this->connection)) {
$connection = $this->connection;
if (strpos($connection, 'test') !== 0) {
$message = sprintf(
'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
$connection,
$this->table
);
throw new CakeException($message);
}
}
$this->init();
}
/**
* {@inheritDoc}
*/
public function connection()
{
return $this->connection;
}
/**
* {@inheritDoc}
*/
public function sourceName()
{
return $this->table;
}
/**
* Initialize the fixture.
*
* @return void
* @throws \Cake\ORM\Exception\MissingTableClassException When importing from a table that does not exist.
*/
public function init()
{
if ($this->table === null) {
$this->table = $this->_tableFromClass();
}
if (empty($this->import) && !empty($this->fields)) {
$this->_schemaFromFields();
}
if (!empty($this->import)) {
$this->_schemaFromImport();
}
if (empty($this->import) && empty($this->fields)) {
$this->_schemaFromReflection();
}
}
/**
* Returns the table name using the fixture class
*
* @return string
*/
protected function _tableFromClass()
{
list(, $class) = namespaceSplit(get_class($this));
preg_match('/^(.*)Fixture$/', $class, $matches);
$table = $class;
if (isset($matches[1])) {
$table = $matches[1];
}
return Inflector::tableize($table);
}
/**
* Build the fixtures table schema from the fields property.
*
* @return void
*/
protected function _schemaFromFields()
{
$connection = ConnectionManager::get($this->connection());
$this->_schema = new TableSchema($this->table);
foreach ($this->fields as $field => $data) {
if ($field === '_constraints' || $field === '_indexes' || $field === '_options') {
continue;
}
$this->_schema->addColumn($field, $data);
}
if (!empty($this->fields['_constraints'])) {
foreach ($this->fields['_constraints'] as $name => $data) {
if (!$connection->supportsDynamicConstraints() || $data['type'] !== TableSchema::CONSTRAINT_FOREIGN) {
$this->_schema->addConstraint($name, $data);
} else {
$this->_constraints[$name] = $data;
}
}
}
if (!empty($this->fields['_indexes'])) {
foreach ($this->fields['_indexes'] as $name => $data) {
$this->_schema->addIndex($name, $data);
}
}
if (!empty($this->fields['_options'])) {
$this->_schema->setOptions($this->fields['_options']);
}
}
/**
* Build fixture schema from a table in another datasource.
*
* @return void
* @throws \Cake\Core\Exception\Exception when trying to import from an empty table.
*/
protected function _schemaFromImport()
{
if (!is_array($this->import)) {
return;
}
$import = $this->import + ['connection' => 'default', 'table' => null, 'model' => null];
if (!empty($import['model'])) {
if (!empty($import['table'])) {
throw new CakeException('You cannot define both table and model.');
}
$import['table'] = TableRegistry::get($import['model'])->getTable();
}
if (empty($import['table'])) {
throw new CakeException('Cannot import from undefined table.');
}
$this->table = $import['table'];
$db = ConnectionManager::get($import['connection'], false);
$schemaCollection = $db->schemaCollection();
$table = $schemaCollection->describe($import['table']);
$this->_schema = $table;
}
/**
* Build fixture schema directly from the datasource
*
* @return void
* @throws \Cake\Core\Exception\Exception when trying to reflect a table that does not exist
*/
protected function _schemaFromReflection()
{
$db = ConnectionManager::get($this->connection());
$schemaCollection = $db->schemaCollection();
$tables = $schemaCollection->listTables();
if (!in_array($this->table, $tables)) {
throw new CakeException(
sprintf(
'Cannot describe schema for table `%s` for fixture `%s` : the table does not exist.',
$this->table,
get_class($this)
)
);
}
$this->_schema = $schemaCollection->describe($this->table);
}
/**
* Gets/Sets the TableSchema instance used by this fixture.
*
* @param \Cake\Database\Schema\TableSchema|\Cake\Database\Schema\TableSchemaInterface|null $schema The table to set.
* @return \Cake\Database\Schema\TableSchema|\Cake\Database\Schema\TableSchemaInterface|null
* @deprecated 3.5.0 Use getTableSchema/setTableSchema instead.
*/
public function schema(TableSchema $schema = null)
{
if ($schema) {
$this->setTableSchema($schema);
}
return $this->getTableSchema();
}
/**
* {@inheritDoc}
*/
public function create(ConnectionInterface $db)
{
if (empty($this->_schema)) {
return false;
}
if (empty($this->import) && empty($this->fields)) {
return true;
}
try {
$queries = $this->_schema->createSql($db);
foreach ($queries as $query) {
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->closeCursor();
}
} catch (Exception $e) {
$msg = sprintf(
'Fixture creation for "%s" failed "%s"',
$this->table,
$e->getMessage()
);
Log::error($msg);
trigger_error($msg, E_USER_WARNING);
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public function drop(ConnectionInterface $db)
{
if (empty($this->_schema)) {
return false;
}
if (empty($this->import) && empty($this->fields)) {
return true;
}
try {
$sql = $this->_schema->dropSql($db);
foreach ($sql as $stmt) {
$db->execute($stmt)->closeCursor();
}
} catch (Exception $e) {
return false;
}
return true;
}
/**
* {@inheritDoc}
*/
public function insert(ConnectionInterface $db)
{
if (isset($this->records) && !empty($this->records)) {
list($fields, $values, $types) = $this->_getRecords();
$query = $db->newQuery()
->insert($fields, $types)
->into($this->table);
foreach ($values as $row) {
$query->values($row);
}
$statement = $query->execute();
$statement->closeCursor();
return $statement;
}
return true;
}
/**
* {@inheritDoc}
*/
public function createConstraints(ConnectionInterface $db)
{
if (empty($this->_constraints)) {
return true;
}
foreach ($this->_constraints as $name => $data) {
$this->_schema->addConstraint($name, $data);
}
$sql = $this->_schema->addConstraintSql($db);
if (empty($sql)) {
return true;
}
foreach ($sql as $stmt) {
$db->execute($stmt)->closeCursor();
}
return true;
}
/**
* {@inheritDoc}
*/
public function dropConstraints(ConnectionInterface $db)
{
if (empty($this->_constraints)) {
return true;
}
$sql = $this->_schema->dropConstraintSql($db);
if (empty($sql)) {
return true;
}
foreach ($sql as $stmt) {
$db->execute($stmt)->closeCursor();
}
foreach ($this->_constraints as $name => $data) {
$this->_schema->dropConstraint($name);
}
return true;
}
/**
* Converts the internal records into data used to generate a query.
*
* @return array
*/
protected function _getRecords()
{
$fields = $values = $types = [];
$columns = $this->_schema->columns();
foreach ($this->records as $record) {
$fields = array_merge($fields, array_intersect(array_keys($record), $columns));
}
$fields = array_values(array_unique($fields));
foreach ($fields as $field) {
$types[$field] = $this->_schema->getColumn($field)['type'];
}
$default = array_fill_keys($fields, null);
foreach ($this->records as $record) {
$values[] = array_merge($default, $record);
}
return [$fields, $values, $types];
}
/**
* {@inheritDoc}
*/
public function truncate(ConnectionInterface $db)
{
$sql = $this->_schema->truncateSql($db);
foreach ($sql as $stmt) {
$db->execute($stmt)->closeCursor();
}
return true;
}
/**
* {@inheritDoc}
*/
public function getTableSchema()
{
return $this->_schema;
}
/**
* {@inheritDoc}
*/
public function setTableSchema(DatabaseTableSchemaInterface $schema)
{
$this->_schema = $schema;
return $this;
}
}