Completed
Pull Request — master (#31)
by David
06:01 queued 02:51
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 Doctrine\DBAL\Platforms\OraclePlatform;
30
use TheCodingMachine\FluidSchema\FluidSchema;
31
use TheCodingMachine\TDBM\Utils\DefaultNamingStrategy;
32
use TheCodingMachine\TDBM\Utils\PathFinder\PathFinder;
33
34
abstract class TDBMAbstractServiceTest extends \PHPUnit_Framework_TestCase
35
{
36
    /**
37
     * @var Connection
38
     */
39
    protected static $dbConnection;
40
41
    /**
42
     * @var TDBMService
43
     */
44
    protected $tdbmService;
45
46
    /**
47
     * @var DummyGeneratorListener
48
     */
49
    private $dummyGeneratorListener;
50
51
    /**
52
     * @var ConfigurationInterface
53
     */
54
    private $configuration;
55
56
    public static function setUpBeforeClass()
57
    {
58
        self::resetConnection();
59
60
        $config = new \Doctrine\DBAL\Configuration();
61
62
        $dbDriver = $GLOBALS['db_driver'];
63
64
        if ($dbDriver === 'pdo_sqlite') {
65
            $dbConnection = self::getConnection();
66
            $dbConnection->exec('PRAGMA foreign_keys = ON;');
67
        } elseif ($dbDriver === 'oci8') {
68
            $connectionParams = array(
69
                'servicename' => 'XE',
70
                'user' => $GLOBALS['db_admin_username'],
71
                // Because of issues in DBAL, admin and normal user password have to be the same.
72
                'password' => $GLOBALS['db_password'],
73
                'host' => $GLOBALS['db_host'],
74
                'port' => $GLOBALS['db_port'],
75
                'driver' => $GLOBALS['db_driver'],
76
                'dbname' => $GLOBALS['db_admin_username'],
77
                'charset' => 'utf-8',
78
            );
79
80
            $adminConn = DriverManager::getConnection($connectionParams, $config);
81
            $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
82
83
            $dbConnection = self::getConnection();
84
        } else {
85
            $connectionParams = array(
86
                'user' => $GLOBALS['db_username'],
87
                'password' => $GLOBALS['db_password'],
88
                'host' => $GLOBALS['db_host'],
89
                'port' => $GLOBALS['db_port'],
90
                'driver' => $dbDriver,
91
            );
92
93
            $adminConn = DriverManager::getConnection($connectionParams, $config);
94
            $adminConn->getSchemaManager()->dropAndCreateDatabase($GLOBALS['db_name']);
95
96
            $connectionParams['dbname'] = $GLOBALS['db_name'];
97
98
            $dbConnection = DriverManager::getConnection($connectionParams, $config);
99
        }
100
101
102
        self::initSchema($dbConnection);
103
    }
104
105
    private static function resetConnection(): void
106
    {
107
        self::$dbConnection = null;
108
    }
109
110
    protected static function getConnection(): Connection
111
    {
112
        if (self::$dbConnection === null) {
113
            $config = new \Doctrine\DBAL\Configuration();
114
115
            $dbDriver = $GLOBALS['db_driver'];
116
117
            if ($dbDriver === 'pdo_sqlite') {
118
                $connectionParams = array(
119
                    'memory' => true,
120
                    'driver' => 'pdo_sqlite',
121
                );
122
                self::$dbConnection = DriverManager::getConnection($connectionParams, $config);
123
            } elseif ($dbDriver === 'oci8') {
124
                $evm = new EventManager();
125
                $evm->addEventSubscriber(new OracleSessionInit(array(
126
                    'NLS_TIME_FORMAT' => 'HH24:MI:SS',
127
                    'NLS_DATE_FORMAT' => 'YYYY-MM-DD HH24:MI:SS',
128
                    'NLS_TIMESTAMP_FORMAT' => 'YYYY-MM-DD HH24:MI:SS',
129
                )));
130
131
                $connectionParams = array(
132
                    'servicename' => 'XE',
133
                    'user' => $GLOBALS['db_username'],
134
                    'password' => $GLOBALS['db_password'],
135
                    'host' => $GLOBALS['db_host'],
136
                    'port' => $GLOBALS['db_port'],
137
                    'driver' => $GLOBALS['db_driver'],
138
                    'dbname' => $GLOBALS['db_name'],
139
                    'charset' => 'utf-8',
140
                );
141
                self::$dbConnection = DriverManager::getConnection($connectionParams, $config, $evm);
142
                self::$dbConnection->setAutoCommit(true);
143
144
            } else {
145
                $connectionParams = array(
146
                    'user' => $GLOBALS['db_username'],
147
                    'password' => $GLOBALS['db_password'],
148
                    'host' => $GLOBALS['db_host'],
149
                    'port' => $GLOBALS['db_port'],
150
                    'driver' => $GLOBALS['db_driver'],
151
                    'dbname' => $GLOBALS['db_name'],
152
                );
153
                self::$dbConnection = DriverManager::getConnection($connectionParams, $config);
154
            }
155
156
        }
157
        return self::$dbConnection;
158
    }
159
160
    protected function onlyMySql()
161
    {
162
        if (!self::getConnection()->getDatabasePlatform() instanceof MySqlPlatform) {
163
            $this->markTestSkipped('MySQL specific test');
164
        }
165
    }
166
167
    protected function setUp()
168
    {
169
        $this->tdbmService = new TDBMService($this->getConfiguration());
170
    }
171
172
    protected function getDummyGeneratorListener() : DummyGeneratorListener
173
    {
174
        if ($this->dummyGeneratorListener === null) {
175
            $this->dummyGeneratorListener = new DummyGeneratorListener();
176
        }
177
        return $this->dummyGeneratorListener;
178
    }
179
180
    protected function getConfiguration() : ConfigurationInterface
181
    {
182
        if ($this->configuration === null) {
183
184
            $this->configuration = new Configuration('TheCodingMachine\\TDBM\\Test\\Dao\\Bean', 'TheCodingMachine\\TDBM\\Test\\Dao', self::getConnection(), $this->getNamingStrategy(), new ArrayCache(), null, null, [$this->getDummyGeneratorListener()]);
185
            $this->configuration->setPathFinder(new PathFinder(null, dirname(__DIR__, 4)));
186
        }
187
        return $this->configuration;
188
    }
189
190
    protected function getNamingStrategy()
191
    {
192
        $strategy = new DefaultNamingStrategy();
193
        $strategy->setBeanPrefix('');
194
        $strategy->setBeanSuffix('Bean');
195
        $strategy->setBaseBeanPrefix('');
196
        $strategy->setBaseBeanSuffix('BaseBean');
197
        $strategy->setDaoPrefix('');
198
        $strategy->setDaoSuffix('Dao');
199
        $strategy->setBaseDaoPrefix('');
200
        $strategy->setBaseDaoSuffix('BaseDao');
201
202
        return $strategy;
203
    }
204
205
    private static function initSchema(Connection $connection): void
206
    {
207
        $fromSchema = $connection->getSchemaManager()->createSchema();
208
        $toSchema = clone $fromSchema;
209
210
        $db = new FluidSchema($toSchema);
211
212
        $db->table('country')
213
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
214
            ->column('label')->string(255);
215
216
        $db->table('person')
217
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
218
            ->column('name')->string(255);
219
220
        if ($connection->getDatabasePlatform() instanceof OraclePlatform) {
221
            $toSchema->getTable('person')
222
                ->addColumn(
223
                    'created_at',
224
                    'datetime',
225
                    ['columnDefinition' => 'TIMESTAMP(0) DEFAULT SYSDATE NOT NULL']
226
                );
227
        } else {
228
            $toSchema->getTable('person')
229
                ->addColumn(
230
                    'created_at',
231
                    'datetime',
232
                    ['columnDefinition' => 'timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP']
233
                );
234
        }
235
236
        $db->table('person')
237
            ->column('modified_at')->datetime()->null()
238
            ->column('order')->integer()->null();
239
240
241
        $db->table('contact')
242
            ->extends('person')
243
            ->column('email')->string(255)
244
            ->column('manager_id')->references('contact')->null();
245
246
        $db->table('users')
247
            ->extends('contact')
248
            ->column('login')->string(255)
249
            ->column('password')->string(255)->null()
250
            ->column('status')->string(10)->null()->default(null)
251
            ->column('country_id')->references('country');
252
253
        $db->table('rights')
254
            ->column('label')->string(255)->primaryKey()->comment('Non autoincrementable primary key');
255
256
        $db->table('roles')
257
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
258
            ->column('name')->string(255)
259
            ->column('created_at')->date()->null()
260
            ->column('status')->boolean()->null()->default(1);
261
262
        $db->table('roles_rights')
263
            ->column('role_id')->references('roles')
264
            ->column('right_label')->references('rights')->then()
265
            ->primaryKey(['role_id', 'right_label']);
266
267
        $db->table('users_roles')
268
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
269
            ->column('user_id')->references('users')
270
            ->column('role_id')->references('roles');
271
272
        $db->table('all_nullable')
273
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
274
            ->column('label')->string(255)->null()
275
            ->column('country_id')->references('country')->null();
276
277
        $db->table('animal')
278
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
279
            ->column('name')->string(45)->index()
280
            ->column('order')->integer()->null();
281
282
        $db->table('dog')
283
            ->extends('animal')
284
            ->column('race')->string(45)->null();
285
286
        $db->table('cat')
287
            ->extends('animal')
288
            ->column('cuteness_level')->integer()->null();
289
290
        $db->table('boats')
291
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
292
            ->column('name')->string(255)
293
            ->column('anchorage_country')->references('country')->notNull();
294
295
        $db->table('sailed_countries')
296
            ->column('boat_id')->references('boats')
297
            ->column('country_id')->references('country')
298
            ->then()->primaryKey(['boat_id', 'country_id']);
299
300
        $db->table('category')
301
            ->column('id')->integer()->primaryKey()->autoIncrement()->comment('@Autoincrement')
302
            ->column('label')->string(255)
303
            ->column('parent_id')->references('category')->null();
304
305
        $db->table('article')
306
            ->column('id')->string(36)->primaryKey()->comment('@UUID')
307
            ->column('content')->string(255);
308
309
        $db->table('article2')
310
            ->column('id')->string(36)->primaryKey()->comment('@UUID v4')
311
            ->column('content')->string(255);
312
313
        $toSchema->getTable('users')
314
            ->addUniqueIndex(['login'], 'users_login_idx')
315
            ->addIndex(['status', 'country_id'], 'users_status_country_idx');
316
317
        // We create the same index twice
318
        // except for Oracle that won't let us create twice the same index.
319
        if (!$connection->getDatabasePlatform() instanceof OraclePlatform) {
320
            $toSchema->getTable('users')
321
                ->addUniqueIndex(['login'], 'users_login_idx_2');
322
        }
323
324
325
        $sqlStmts = $toSchema->getMigrateFromSql($fromSchema, $connection->getDatabasePlatform());
326
327
        foreach ($sqlStmts as $sqlStmt) {
328
            $connection->exec($sqlStmt);
329
        }
330
331
        $connection->insert('country', [
332
            'label' => 'France',
333
        ]);
334
        $connection->insert('country', [
335
            'label' => 'UK',
336
        ]);
337
        $connection->insert('country', [
338
            'label' => 'Jamaica',
339
        ]);
340
341
        $connection->insert('person', [
342
            'name' => 'John Smith',
343
            'created_at' => '2015-10-24 11:57:13',
344
        ]);
345
        $connection->insert('person', [
346
            'name' => 'Jean Dupont',
347
            'created_at' => '2015-10-24 11:57:13',
348
        ]);
349
        $connection->insert('person', [
350
            'name' => 'Robert Marley',
351
            'created_at' => '2015-10-24 11:57:13',
352
        ]);
353
        $connection->insert('person', [
354
            'name' => 'Bill Shakespeare',
355
            'created_at' => '2015-10-24 11:57:13',
356
        ]);
357
358
        $connection->insert('contact', [
359
            'id' => 1,
360
            'email' => '[email protected]',
361
            'manager_id' => null,
362
        ]);
363
        $connection->insert('contact', [
364
            'id' => 2,
365
            'email' => '[email protected]',
366
            'manager_id' => null,
367
        ]);
368
        $connection->insert('contact', [
369
            'id' => 3,
370
            'email' => '[email protected]',
371
            'manager_id' => null,
372
        ]);
373
        $connection->insert('contact', [
374
            'id' => 4,
375
            'email' => '[email protected]',
376
            'manager_id' => 1,
377
        ]);
378
379
        $connection->insert('rights', [
380
            'label' => 'CAN_SING',
381
        ]);
382
        $connection->insert('rights', [
383
            'label' => 'CAN_WRITE',
384
        ]);
385
386
        $connection->insert('roles', [
387
            'name' => 'Admins',
388
            'created_at' => '2015-10-24'
389
        ]);
390
        $connection->insert('roles', [
391
            'name' => 'Writers',
392
            'created_at' => '2015-10-24'
393
        ]);
394
        $connection->insert('roles', [
395
            'name' => 'Singers',
396
            'created_at' => '2015-10-24'
397
        ]);
398
399
        $connection->insert('roles_rights', [
400
            'role_id' => 1,
401
            'right_label' => 'CAN_SING'
402
        ]);
403
        $connection->insert('roles_rights', [
404
            'role_id' => 3,
405
            'right_label' => 'CAN_SING'
406
        ]);
407
        $connection->insert('roles_rights', [
408
            'role_id' => 1,
409
            'right_label' => 'CAN_WRITE'
410
        ]);
411
        $connection->insert('roles_rights', [
412
            'role_id' => 2,
413
            'right_label' => 'CAN_WRITE'
414
        ]);
415
416
        $connection->insert('users', [
417
            'id' => 1,
418
            'login' => 'john.smith',
419
            'password' => null,
420
            'status' => 'on',
421
            'country_id' => 2
422
        ]);
423
        $connection->insert('users', [
424
            'id' => 2,
425
            'login' => 'jean.dupont',
426
            'password' => null,
427
            'status' => 'on',
428
            'country_id' => 1
429
        ]);
430
        $connection->insert('users', [
431
            'id' => 3,
432
            'login' => 'robert.marley',
433
            'password' => null,
434
            'status' => 'off',
435
            'country_id' => 3
436
        ]);
437
        $connection->insert('users', [
438
            'id' => 4,
439
            'login' => 'bill.shakespeare',
440
            'password' => null,
441
            'status' => 'off',
442
            'country_id' => 2
443
        ]);
444
445
        $connection->insert('users_roles', [
446
            'user_id' => 1,
447
            'role_id' => 1,
448
        ]);
449
        $connection->insert('users_roles', [
450
            'user_id' => 2,
451
            'role_id' => 1,
452
        ]);
453
        $connection->insert('users_roles', [
454
            'user_id' => 3,
455
            'role_id' => 3,
456
        ]);
457
        $connection->insert('users_roles', [
458
            'user_id' => 4,
459
            'role_id' => 2,
460
        ]);
461
        $connection->insert('users_roles', [
462
            'user_id' => 3,
463
            'role_id' => 2,
464
        ]);
465
    }
466
}
467