Completed
Pull Request — master (#31)
by David
06:26 queued 03:04
created

TDBMAbstractServiceTest::resetConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 Copyright (C) 2006-2014 David Négrier - THE CODING MACHINE
5
6
This program is free software; you can redistribute it and/or modify
7
it under the terms of the GNU General Public License as published by
8
the Free Software Foundation; either version 2 of the License, or
9
(at your option) any later version.
10
11
This program is distributed in the hope that it will be useful,
12
but WITHOUT ANY WARRANTY; without even the implied warranty of
13
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
GNU General Public License for more details.
15
16
You should have received a copy of the GNU General Public License
17
along with this program; if not, write to the Free Software
18
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
*/
20
21
namespace TheCodingMachine\TDBM;
22
23
use Doctrine\Common\Cache\ArrayCache;
24
use Doctrine\Common\EventManager;
25
use Doctrine\DBAL\Connection;
26
use Doctrine\DBAL\DriverManager;
27
use Doctrine\DBAL\Event\Listeners\OracleSessionInit;
28
use Doctrine\DBAL\Platforms\MySqlPlatform;
29
use TheCodingMachine\FluidSchema\FluidSchema;
30
use TheCodingMachine\TDBM\Utils\DefaultNamingStrategy;
31
use TheCodingMachine\TDBM\Utils\PathFinder\PathFinder;
32
33
abstract class TDBMAbstractServiceTest extends \PHPUnit_Framework_TestCase
34
{
35
    /**
36
     * @var Connection
37
     */
38
    protected static $dbConnection;
39
40
    /**
41
     * @var TDBMService
42
     */
43
    protected $tdbmService;
44
45
    /**
46
     * @var DummyGeneratorListener
47
     */
48
    private $dummyGeneratorListener;
49
50
    /**
51
     * @var ConfigurationInterface
52
     */
53
    private $configuration;
54
55
    public static function setUpBeforeClass()
56
    {
57
        self::resetConnection();
58
59
        $config = new \Doctrine\DBAL\Configuration();
60
61
        $dbDriver = $GLOBALS['db_driver'];
62
63
        if ($dbDriver === 'pdo_sqlite') {
64
            $dbConnection = self::getConnection();
65
            $dbConnection->exec('PRAGMA foreign_keys = ON;');
66
        } elseif ($dbDriver === 'oci8') {
67
            // In the case of Oracle, there is no easy way to reset the database. Let's assume it is empty (this is true with Travis tests)
68
            $dbConnection = self::getConnection();
69
        } else {
70
            $connectionParams = array(
71
                'user' => $GLOBALS['db_username'],
72
                'password' => $GLOBALS['db_password'],
73
                'host' => $GLOBALS['db_host'],
74
                'port' => $GLOBALS['db_port'],
75
                'driver' => $dbDriver,
76
            );
77
78
            $adminConn = DriverManager::getConnection($connectionParams, $config);
79
            $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
80
81
            $connectionParams['dbname'] = $GLOBALS['db_name'];
82
83
            $dbConnection = DriverManager::getConnection($connectionParams, $config);
84
        }
85
86
87
        self::initSchema($dbConnection);
88
    }
89
90
    private static function resetConnection(): void
91
    {
92
        self::$dbConnection = null;
93
    }
94
95
    protected static function getConnection(): Connection
96
    {
97
        if (self::$dbConnection === null) {
98
            $config = new \Doctrine\DBAL\Configuration();
99
100
            $dbDriver = $GLOBALS['db_driver'];
101
102
            if ($dbDriver === 'pdo_sqlite') {
103
                $connectionParams = array(
104
                    'memory' => true,
105
                    'driver' => 'pdo_sqlite',
106
                );
107
            } elseif ($dbDriver === 'oci8') {
108
                $evm = new EventManager();
109
                $evm->addEventSubscriber(new OracleSessionInit(array(
110
                    'NLS_TIME_FORMAT' => 'HH24:MI:SS',
111
                )));
112
113
                $connectionParams = array(
114
                    'servicename' => 'XE',
115
                    'user' => $GLOBALS['db_username'],
116
                    'password' => $GLOBALS['db_password'],
117
                    'host' => $GLOBALS['db_host'],
118
                    'port' => $GLOBALS['db_port'],
119
                    'driver' => $GLOBALS['db_driver'],
120
                    'dbname' => $GLOBALS['db_name'],
121
                    'charset' => 'utf-8',
122
                );
123
                $connection = DriverManager::getConnection($connectionParams, $config, $evm);
124
                $connection->setAutoCommit(true);
125
126
            } else {
127
                $connectionParams = array(
128
                    'user' => $GLOBALS['db_username'],
129
                    'password' => $GLOBALS['db_password'],
130
                    'host' => $GLOBALS['db_host'],
131
                    'port' => $GLOBALS['db_port'],
132
                    'driver' => $GLOBALS['db_driver'],
133
                    'dbname' => $GLOBALS['db_name'],
134
                );
135
            }
136
137
            self::$dbConnection = DriverManager::getConnection($connectionParams, $config);
138
        }
139
        return self::$dbConnection;
140
    }
141
142
    protected function onlyMySql()
143
    {
144
        if (!self::getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
145
            $this->markTestSkipped('MySQL specific test');
146
        }
147
    }
148
149
    protected function setUp()
150
    {
151
        $this->tdbmService = new TDBMService($this->getConfiguration());
152
    }
153
154
    protected function getDummyGeneratorListener() : DummyGeneratorListener
155
    {
156
        if ($this->dummyGeneratorListener === null) {
157
            $this->dummyGeneratorListener = new DummyGeneratorListener();
158
        }
159
        return $this->dummyGeneratorListener;
160
    }
161
162
    protected function getConfiguration() : ConfigurationInterface
163
    {
164
        if ($this->configuration === null) {
165
166
            $this->configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), $this->getNamingStrategy(), new ArrayCache(), null, null, [$this->getDummyGeneratorListener()]);
167
            $this->configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 4)));
168
        }
169
        return $this->configuration;
170
    }
171
172
    protected function getNamingStrategy()
173
    {
174
        $strategy = new DefaultNamingStrategy();
175
        $strategy->setBeanPrefix('');
176
        $strategy->setBeanSuffix('Bean');
177
        $strategy->setBaseBeanPrefix('');
178
        $strategy->setBaseBeanSuffix('BaseBean');
179
        $strategy->setDaoPrefix('');
180
        $strategy->setDaoSuffix('Dao');
181
        $strategy->setBaseDaoPrefix('');
182
        $strategy->setBaseDaoSuffix('BaseDao');
183
184
        return $strategy;
185
    }
186
187
    private static function initSchema(Connection $connection): void
188
    {
189
        $fromSchema = $connection->getSchemaManager()->createSchema();
190
        $toSchema = clone $fromSchema;
191
192
        $db = new FluidSchema($toSchema);
193
194
        $db->table('country')
195
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
196
            ->column('label')->string(255);
197
198
        $db->table('person')
199
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
200
            ->column('name')->string(255);
201
202
        $toSchema->getTable('person')
203
            ->addColumn(
204
                'created_at',
205
                'datetime',
206
                ['columnDefinition' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP']
207
            );
208
209
        $db->table('person')
210
            ->column('modified_at')->datetime()->null()
211
            ->column('order')->integer()->null();
212
213
214
        $db->table('contact')
215
            ->extends('person')
216
            ->column('email')->string(255)
217
            ->column('manager_id')->references('contact')->null();
218
219
        $db->table('users')
220
            ->extends('contact')
221
            ->column('login')->string(255)
222
            ->column('password')->string(255)->null()
223
            ->column('status')->string(10)->null()->default(null)
224
            ->column('country_id')->references('country');
225
226
        $db->table('rights')
227
            ->column('label')->string(255)->primaryKey()->comment('Non autoincrementable primary key');
228
229
        $db->table('roles')
230
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
231
            ->column('name')->string(255)
232
            ->column('created_at')->date()->null()
233
            ->column('status')->boolean()->null()->default(1);
234
235
        $db->table('roles_rights')
236
            ->column('role_id')->references('roles')
237
            ->column('right_label')->references('rights')->then()
238
            ->primaryKey(['role_id', 'right_label']);
239
240
        $db->table('users_roles')
241
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
242
            ->column('user_id')->references('users')
243
            ->column('role_id')->references('roles');
244
245
        $db->table('all_nullable')
246
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
247
            ->column('label')->string(255)->null()
248
            ->column('country_id')->references('country')->null();
249
250
        $db->table('animal')
251
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
252
            ->column('name')->string(45)->index()
253
            ->column('order')->integer()->null();
254
255
        $db->table('dog')
256
            ->extends('animal')
257
            ->column('race')->string(45)->null();
258
259
        $db->table('cat')
260
            ->extends('animal')
261
            ->column('cuteness_level')->integer()->null();
262
263
        $db->table('boats')
264
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
265
            ->column('name')->string(255)
266
            ->column('anchorage_country')->references('country')->notNull();
267
268
        $db->table('sailed_countries')
269
            ->column('boat_id')->references('boats')
270
            ->column('country_id')->references('country')
271
            ->then()->primaryKey(['boat_id', 'country_id']);
272
273
        $db->table('category')
274
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
275
            ->column('label')->string(255)
276
            ->column('parent_id')->references('category')->null();
277
278
        $db->table('article')
279
            ->column('id')->string(36)->primaryKey()->comment('@UUID')
280
            ->column('content')->string(255);
281
282
        $db->table('article2')
283
            ->column('id')->string(36)->primaryKey()->comment('@UUID v4')
284
            ->column('content')->string(255);
285
286
        $toSchema->getTable('users')
287
            ->addUniqueIndex(['login'], 'users_login_idx')
288
            ->addUniqueIndex(['login'], 'users_login_idx_2') // We create the same index twice
289
            ->addIndex(['status', 'country_id'], 'users_status_country_idx');
290
291
        $sqlStmts = $toSchema->getMigrateFromSql($fromSchema, $connection->getDatabasePlatform());
292
293
        foreach ($sqlStmts as $sqlStmt) {
294
            $connection->exec($sqlStmt);
295
        }
296
297
        $connection->insert('country', [
298
            'label' => 'France',
299
        ]);
300
        $connection->insert('country', [
301
            'label' => 'UK',
302
        ]);
303
        $connection->insert('country', [
304
            'label' => 'Jamaica',
305
        ]);
306
307
        $connection->insert('person', [
308
            'name' => 'John Smith',
309
            'created_at' => '2015-10-24 11:57:13',
310
        ]);
311
        $connection->insert('person', [
312
            'name' => 'Jean Dupont',
313
            'created_at' => '2015-10-24 11:57:13',
314
        ]);
315
        $connection->insert('person', [
316
            'name' => 'Robert Marley',
317
            'created_at' => '2015-10-24 11:57:13',
318
        ]);
319
        $connection->insert('person', [
320
            'name' => 'Bill Shakespeare',
321
            'created_at' => '2015-10-24 11:57:13',
322
        ]);
323
324
        $connection->insert('contact', [
325
            'id' => 1,
326
            'email' => '[email protected]',
327
            'manager_id' => null,
328
        ]);
329
        $connection->insert('contact', [
330
            'id' => 2,
331
            'email' => '[email protected]',
332
            'manager_id' => null,
333
        ]);
334
        $connection->insert('contact', [
335
            'id' => 3,
336
            'email' => '[email protected]',
337
            'manager_id' => null,
338
        ]);
339
        $connection->insert('contact', [
340
            'id' => 4,
341
            'email' => '[email protected]',
342
            'manager_id' => 1,
343
        ]);
344
345
        $connection->insert('rights', [
346
            'label' => 'CAN_SING',
347
        ]);
348
        $connection->insert('rights', [
349
            'label' => 'CAN_WRITE',
350
        ]);
351
352
        $connection->insert('roles', [
353
            'name' => 'Admins',
354
            'created_at' => '2015-10-24'
355
        ]);
356
        $connection->insert('roles', [
357
            'name' => 'Writers',
358
            'created_at' => '2015-10-24'
359
        ]);
360
        $connection->insert('roles', [
361
            'name' => 'Singers',
362
            'created_at' => '2015-10-24'
363
        ]);
364
365
        $connection->insert('roles_rights', [
366
            'role_id' => 1,
367
            'right_label' => 'CAN_SING'
368
        ]);
369
        $connection->insert('roles_rights', [
370
            'role_id' => 3,
371
            'right_label' => 'CAN_SING'
372
        ]);
373
        $connection->insert('roles_rights', [
374
            'role_id' => 1,
375
            'right_label' => 'CAN_WRITE'
376
        ]);
377
        $connection->insert('roles_rights', [
378
            'role_id' => 2,
379
            'right_label' => 'CAN_WRITE'
380
        ]);
381
382
        $connection->insert('users', [
383
            'id' => 1,
384
            'login' => 'john.smith',
385
            'password' => null,
386
            'status' => 'on',
387
            'country_id' => 2
388
        ]);
389
        $connection->insert('users', [
390
            'id' => 2,
391
            'login' => 'jean.dupont',
392
            'password' => null,
393
            'status' => 'on',
394
            'country_id' => 1
395
        ]);
396
        $connection->insert('users', [
397
            'id' => 3,
398
            'login' => 'robert.marley',
399
            'password' => null,
400
            'status' => 'off',
401
            'country_id' => 3
402
        ]);
403
        $connection->insert('users', [
404
            'id' => 4,
405
            'login' => 'bill.shakespeare',
406
            'password' => null,
407
            'status' => 'off',
408
            'country_id' => 2
409
        ]);
410
411
        $connection->insert('users_roles', [
412
            'user_id' => 1,
413
            'role_id' => 1,
414
        ]);
415
        $connection->insert('users_roles', [
416
            'user_id' => 2,
417
            'role_id' => 1,
418
        ]);
419
        $connection->insert('users_roles', [
420
            'user_id' => 3,
421
            'role_id' => 3,
422
        ]);
423
        $connection->insert('users_roles', [
424
            'user_id' => 4,
425
            'role_id' => 2,
426
        ]);
427
        $connection->insert('users_roles', [
428
            'user_id' => 3,
429
            'role_id' => 2,
430
        ]);
431
    }
432
}
433