Completed
Pull Request — master (#31)
by David
07:02 queued 03:52
created

TDBMAbstractServiceTest   B

Complexity

Total Complexity 19

Size/Duplication

Total Lines 409
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 409
rs 7.8571
wmc 19
lcom 1
cbo 17

9 Methods

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