Passed
Pull Request — master (#31)
by David
06:24 queued 03:06
created

TDBMAbstractServiceTest::initSchema()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 261
Code Lines 189

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 189
c 3
b 0
f 0
nc 8
nop 1
dl 0
loc 261
rs 8.1935

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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