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