forked from concretecms/concretecms
/
ConcreteDatabaseTestCase.php
executable file
·354 lines (290 loc) · 10.2 KB
/
ConcreteDatabaseTestCase.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
<?php
use Concrete\Core\Database\DatabaseStructureManager;
use Concrete\Core\Database\Schema\Schema;
use Doctrine\DBAL\Driver\Connection;
use Doctrine\DBAL\Driver\PDOConnection;
use Concrete\Core\Support\Facade\Application;
use Doctrine\DBAL\Platforms\MySqlPlatform;
use Doctrine\ORM\EntityManagerInterface;
use Imagine\Exception\RuntimeException;
class ConcreteDatabaseTestCase extends PHPUnit_Extensions_Database_TestCase
{
/** @var Connection The cached database connection */
public static $connection = null;
/** @var bool[] Keys are tables that currently exist */
public static $existingTables = [];
/** @var bool[] Keys are entites that currently exist */
public static $existingEntites = [];
/** @var array[] Table data cache */
public static $tableData = [];
/** @var string[] The tables to import from /concrete/config/db.xml */
protected $tables = [];
/** @var string[] The fixtures to import */
protected $fixtures = [];
/** @var string[] The Entities to import */
protected $metadatas = [];
/**
* Get the connection to use
*
* @return \Doctrine\DBAL\Driver\Connection
*/
protected function connection()
{
if (!static::$connection) {
static::$connection = Application::make('database')->connection('travis');
}
return static::$connection;
}
/**
* Returns the test database connection.
*
* @return PHPUnit_Extensions_Database_DB_IDatabaseConnection
* @throws \Imagine\Exception\RuntimeException
*/
protected function getConnection()
{
$connection = $this->connection()->getWrappedConnection();
if (!$connection instanceof PDOConnection) {
throw new RuntimeException('Invalid connection type.');
}
return $this->createDefaultDBConnection($connection, 'test');
}
/**
* Returns the test dataset.
*
* @return PHPUnit_Extensions_Database_DataSet_IDataSet
*/
protected function getDataSet()
{
$dataSet = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet();
$this->importFixtures($dataSet);
return $dataSet;
}
/**
* Set up before any tests run
*/
public static function setUpBeforeClass()
{
// Make sure tables are imported
$testCase = new Static();
$testCase->importTables();
$testCase->importMetadatas();
// Call parent setup
parent::setUpBeforeClass();
}
/**
* Tear down after class has completed
*/
public static function tearDownAfterClass()
{
// Make sure tables are removed
$testCase = new Static();
$testCase->removeTables();
// Call parent teardown
parent::tearDownAfterClass();
}
/**
* Import tables from $this->tables
*/
protected function importTables()
{
$connection = $this->connection();
// Filter out any tables that have already been imported
$tables = array_filter($this->tables, function($table) {
return !isset(static::$existingTables[$table]);
});
if ($tables) {
// Try to extract the tables
if (!$xml = $this->extractTableData($tables)) {
throw new RuntimeException('Invalid tables: ' . json_encode($tables));
}
// Import any extracted tables
$this->importTableXML($xml, $connection);
// Check for special `BlockType` case
if (in_array('BlockTypes', $tables, false)) {
$xml = simplexml_load_file(DIR_BASE_CORE . '/blocks/core_scrapbook_display/db.xml');
$this->importTableXML($xml, $connection);
}
}
}
/**
* Remove all existing tables
*/
protected function removeTables()
{
$connection = $this->connection();
// Get all existing tables
$tables = $connection->query('show tables')->fetchAll();
$tables = array_map('array_shift', $tables);
// Turn off foreign key checks
$connection->exec('SET FOREIGN_KEY_CHECKS = 0');
foreach ($tables as $table) {
// Drop tables
$connection->exec("DROP TABLE `{$table}`");
}
// Reset foreign key checks on
$connection->exec('SET FOREIGN_KEY_CHECKS = 1');
// Clear exists cache
static::$existingTables = [];
static::$existingEntites = [];
}
/**
* Extract the table data from the db.xml
*
* @param array $tables
* @return array|null
*/
protected function extractTableData(array $tables)
{
// If there are no tables, there's no reason to scan the XML
if (!count($tables)) {
return null;
}
// Initialize an xml document
$partial = new SimpleXMLElement('<schema xmlns="http://www.concrete5.org/doctrine-xml/0.5" />');
// Open the db.xml file
$xml1 = simplexml_load_file(DIR_BASE_CORE . '/config/db.xml');
$importedTables = [];
// Loop through tables that exist in the document
foreach ($xml1->table as $table) {
$name = (string)$table['name'];
// If this table is being requested
if (in_array($name, $tables, false)) {
$this->appendXML($partial, $table);
// Remove the table from our list of tables
$tables = array_filter($tables, function($name) use ($table) {
return $name !== $table;
});
// Track that we actually have tables to import
$importedTables[] = $name;
static::$existingTables[$name] = true;
}
if (!$tables) {
break;
}
}
// Return the partial only if there are tables to import
return $importedTables ? $partial : null;
}
/**
* Import needed tables
*
* @param SimpleXMLElement $xml
* @param Connection $connection
* @internal param $partial
*/
protected function importTableXML(SimpleXMLElement $xml, Connection $connection)
{
// Convert the given partial into sql create statements
$schema = Schema::loadFromXMLElement($xml, $connection);
$queries = $schema->toSql(new MySqlPlatform());
// Run queries
foreach ($queries as $query) {
$connection->query($query);
}
}
/**
* @param \PHPUnit_Extensions_Database_DataSet_CompositeDataSet $dataSet
*/
protected function importFixtures(PHPUnit_Extensions_Database_DataSet_CompositeDataSet $dataSet)
{
$fixtures = $this->fixtures;
$reflectionClass = new ReflectionClass(get_called_class());
$fixturePath = dirname($reflectionClass->getFilename()) . DIRECTORY_SEPARATOR . 'fixtures';
foreach ((array) $fixtures as $fixture) {
$path = $fixturePath . DIRECTORY_SEPARATOR . "$fixture.xml";
$ds = $this->createMySQLXMLDataSet($path);
$dataSet->addDataSet($ds);
}
}
/**
* Import requested metadatas
*/
protected function importMetadatas()
{
$sm = Application::make(DatabaseStructureManager::class);
if ($metadatas = $this->getMetadatas()) {
$sm->installDatabaseFor($metadatas);
}
}
/**
* Gets the metadatas to import
* @return array
*/
protected function getMetadatas()
{
$metadatas = [];
$install = $this->metadatas;
// If there are metadatas to import
if ($this->metadatas && is_array($this->metadatas)) {
/** @var EntityManagerInterface $manager */
$manager = Application::make(EntityManagerInterface::class);
$factory = $manager->getMetadataFactory();
// Loop through all metadata
foreach ($factory->getAllMetadata() as $meta) {
if (!isset(self::$existingEntites[$meta->getName()]) && in_array($meta->getName(), $install, false)) {
$metadatas[] = $meta;
// Remove this from the list of entities to install
$install = array_filter($install, function($name) use ($meta) {
return $name !== $meta->getName();
});
// Track that we've created this metadata
self::$existingEntites[$meta->getName()] = true;
}
// If no more entities to install, lets break
if (!$install) {
break;
}
}
}
return $metadatas;
}
public function tearDown()
{
parent::tearDown();
\ORM::entityManager('core')->clear();
\CacheLocal::flush();
}
/**
* Append an xml onto another xml
* @param \SimpleXMLElement $root
* @param \SimpleXMLElement $new
*/
protected function appendXML(SimpleXMLElement $root, SimpleXMLElement $new)
{
$node = $root->addChild($new->getName(), (string) $new);
foreach ($new->attributes() as $attr => $value) {
$node->addAttribute($attr, $value);
}
foreach ($new->children() as $ch) {
$this->appendXML($node, $ch);
}
}
protected function debug()
{
$this->connection()->getConfiguration()->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
}
/**
* Truncate all known databases
* @param null|array $tables The tables to truncate
*/
protected function truncateTables($tables = null)
{
$connection = $this->connection();
if ($tables === null) {
// Get all existing tables
$tables = $connection->query('show tables')->fetchAll();
$tables = array_map(function ($table) {
return array_shift($table);
}, $tables);
}
// Turn off foreign key checks
$connection->exec('SET FOREIGN_KEY_CHECKS = 0');
foreach ($tables as $table) {
// Drop tables
$connection->exec("TRUNCATE TABLE `{$table}`");
}
// Reset foreign key checks on
$connection->exec('SET FOREIGN_KEY_CHECKS = 1');
}
}