Completed
Pull Request — master (#31)
by David
15:58 queued 06:00
created

TDBMAbstractServiceTest::getConnection()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 48
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

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