Completed
Pull Request — master (#31)
by David
09:35 queued 02:51
created

TDBMAbstractServiceTest::getNamingStrategy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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