Completed
Pull Request — master (#981)
by Andreas
10:24
created

testLoadMultipleConnections()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 59
rs 8.8945
c 0
b 0
f 0
cc 1
nc 1
nop 0

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
namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection;
4
5
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DbalSchemaFilterPass;
6
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass;
7
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
8
use Doctrine\DBAL\Configuration;
9
use Doctrine\DBAL\Schema\AbstractAsset;
10
use Doctrine\ORM\EntityManager;
11
use PHPUnit\Framework\TestCase;
12
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
13
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
14
use Symfony\Component\Cache\DoctrineProvider;
15
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
16
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
17
use Symfony\Component\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\Definition;
19
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
20
use Symfony\Component\DependencyInjection\Reference;
21
use Symfony\Component\DependencyInjection\ServiceLocator;
22
23
abstract class AbstractDoctrineExtensionTest extends TestCase
24
{
25
    abstract protected function loadFromFile(ContainerBuilder $container, $file);
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
26
27
    public function testDbalLoadFromXmlMultipleConnections()
28
    {
29
        $container = $this->loadContainer('dbal_service_multiple_connections');
30
31
        // doctrine.dbal.mysql_connection
32
        $config = $container->getDefinition('doctrine.dbal.mysql_connection')->getArgument(0);
33
34
        $this->assertEquals('mysql_s3cr3t', $config['password']);
35
        $this->assertEquals('mysql_user', $config['user']);
36
        $this->assertEquals('mysql_db', $config['dbname']);
37
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
38
39
        // doctrine.dbal.sqlite_connection
40
        $config = $container->getDefinition('doctrine.dbal.sqlite_connection')->getArgument(0);
41
        $this->assertSame('pdo_sqlite', $config['driver']);
42
        $this->assertSame('sqlite_db', $config['dbname']);
43
        $this->assertSame('sqlite_user', $config['user']);
44
        $this->assertSame('sqlite_s3cr3t', $config['password']);
45
        $this->assertSame('/tmp/db.sqlite', $config['path']);
46
        $this->assertTrue($config['memory']);
47
48
        // doctrine.dbal.oci8_connection
49
        $config = $container->getDefinition('doctrine.dbal.oci_connection')->getArgument(0);
50
        $this->assertSame('oci8', $config['driver']);
51
        $this->assertSame('oracle_db', $config['dbname']);
52
        $this->assertSame('oracle_user', $config['user']);
53
        $this->assertSame('oracle_s3cr3t', $config['password']);
54
        $this->assertSame('oracle_service', $config['servicename']);
55
        $this->assertTrue($config['service']);
56
        $this->assertTrue($config['pooled']);
57
        $this->assertSame('utf8', $config['charset']);
58
59
        // doctrine.dbal.ibmdb2_connection
60
        $config = $container->getDefinition('doctrine.dbal.ibmdb2_connection')->getArgument(0);
61
        $this->assertSame('ibm_db2', $config['driver']);
62
        $this->assertSame('ibmdb2_db', $config['dbname']);
63
        $this->assertSame('ibmdb2_user', $config['user']);
64
        $this->assertSame('ibmdb2_s3cr3t', $config['password']);
65
        $this->assertSame('TCPIP', $config['protocol']);
66
67
        // doctrine.dbal.pgsql_connection
68
        $config = $container->getDefinition('doctrine.dbal.pgsql_connection')->getArgument(0);
69
        $this->assertSame('pdo_pgsql', $config['driver']);
70
        $this->assertSame('pgsql_schema', $config['dbname']);
71
        $this->assertSame('pgsql_user', $config['user']);
72
        $this->assertSame('pgsql_s3cr3t', $config['password']);
73
        $this->assertSame('pgsql_db', $config['default_dbname']);
74
        $this->assertSame('require', $config['sslmode']);
75
        $this->assertSame('postgresql-ca.pem', $config['sslrootcert']);
76
        $this->assertSame('postgresql-cert.pem', $config['sslcert']);
77
        $this->assertSame('postgresql-key.pem', $config['sslkey']);
78
        $this->assertSame('postgresql.crl', $config['sslcrl']);
79
        $this->assertSame('utf8', $config['charset']);
80
81
        // doctrine.dbal.sqlanywhere_connection
82
        $config = $container->getDefinition('doctrine.dbal.sqlanywhere_connection')->getArgument(0);
83
        $this->assertSame('sqlanywhere', $config['driver']);
84
        $this->assertSame('localhost', $config['host']);
85
        $this->assertSame(2683, $config['port']);
86
        $this->assertSame('sqlanywhere_server', $config['server']);
87
        $this->assertSame('sqlanywhere_db', $config['dbname']);
88
        $this->assertSame('sqlanywhere_user', $config['user']);
89
        $this->assertSame('sqlanywhere_s3cr3t', $config['password']);
90
        $this->assertTrue($config['persistent']);
91
        $this->assertSame('utf8', $config['charset']);
92
    }
93
94
    public function testDbalLoadFromXmlSingleConnections()
95
    {
96
        $container = $this->loadContainer('dbal_service_single_connection');
97
98
        // doctrine.dbal.mysql_connection
99
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
100
101
        $this->assertEquals('mysql_s3cr3t', $config['password']);
102
        $this->assertEquals('mysql_user', $config['user']);
103
        $this->assertEquals('mysql_db', $config['dbname']);
104
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
105
        $this->assertEquals('5.6.20', $config['serverVersion']);
106
    }
107
108
    public function testDbalLoadSingleMasterSlaveConnection()
109
    {
110
        $container = $this->loadContainer('dbal_service_single_master_slave_connection');
111
112
        // doctrine.dbal.mysql_connection
113
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
114
115
        $this->assertEquals('Doctrine\\DBAL\\Connections\\MasterSlaveConnection', $param['wrapperClass']);
116
        $this->assertTrue($param['keepSlave']);
117
        $this->assertEquals(
118
            [
119
                'user' => 'mysql_user',
120
                'password' => 'mysql_s3cr3t',
121
                'port' => null,
122
                'dbname' => 'mysql_db',
123
                'host' => 'localhost',
124
                'unix_socket' => '/path/to/mysqld.sock',
125
            ],
126
            $param['master']
127
        );
128
        $this->assertEquals(
129
            [
130
                'user' => 'slave_user',
131
                'password' => 'slave_s3cr3t',
132
                'port' => null,
133
                'dbname' => 'slave_db',
134
                'host' => 'localhost',
135
                'unix_socket' => '/path/to/mysqld_slave.sock',
136
            ],
137
            $param['slaves']['slave1']
138
        );
139
        $this->assertEquals(['engine' => 'InnoDB'], $param['defaultTableOptions']);
140
    }
141
142
    public function testDbalLoadPoolShardingConnection()
143
    {
144
        $container = $this->loadContainer('dbal_service_pool_sharding_connection');
145
146
        // doctrine.dbal.mysql_connection
147
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
148
149
        $this->assertEquals('Doctrine\\DBAL\\Sharding\\PoolingShardConnection', $param['wrapperClass']);
150
        $this->assertEquals(new Reference('foo.shard_choser'), $param['shardChoser']);
151
        $this->assertEquals(
152
            [
153
                'user' => 'mysql_user',
154
                'password' => 'mysql_s3cr3t',
155
                'port' => null,
156
                'dbname' => 'mysql_db',
157
                'host' => 'localhost',
158
                'unix_socket' => '/path/to/mysqld.sock',
159
            ],
160
            $param['global']
161
        );
162
        $this->assertEquals(
163
            [
164
                'user' => 'shard_user',
165
                'password' => 'shard_s3cr3t',
166
                'port' => null,
167
                'dbname' => 'shard_db',
168
                'host' => 'localhost',
169
                'unix_socket' => '/path/to/mysqld_shard.sock',
170
                'id' => 1,
171
            ],
172
            $param['shards'][0]
173
        );
174
        $this->assertEquals(['engine' => 'InnoDB'], $param['defaultTableOptions']);
175
    }
176
177
    public function testDbalLoadSavepointsForNestedTransactions()
178
    {
179
        $container = $this->loadContainer('dbal_savepoints');
180
181
        $calls = $container->getDefinition('doctrine.dbal.savepoints_connection')->getMethodCalls();
182
        $this->assertCount(1, $calls);
0 ignored issues
show
Documentation introduced by
$calls is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
183
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
184
        $this->assertTrue($calls[0][1][0]);
185
186
        $calls = $container->getDefinition('doctrine.dbal.nosavepoints_connection')->getMethodCalls();
187
        $this->assertCount(0, $calls);
0 ignored issues
show
Documentation introduced by
$calls is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188
189
        $calls = $container->getDefinition('doctrine.dbal.notset_connection')->getMethodCalls();
190
        $this->assertCount(0, $calls);
0 ignored issues
show
Documentation introduced by
$calls is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
191
    }
192
193
    /**
194
     * @group legacy
195
     */
196
    public function testLoadSimpleSingleConnection()
197
    {
198
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
199
200
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
201
202
        $this->assertDICConstructorArguments($definition, [
203
            [
204
                'dbname' => 'db',
205
                'host' => 'localhost',
206
                'port' => null,
207
                'user' => 'root',
208
                'password' => null,
209
                'driver' => 'pdo_mysql',
210
                'driverOptions' => [],
211
                'defaultTableOptions' => [],
212
            ],
213
            new Reference('doctrine.dbal.default_connection.configuration'),
214
            new Reference('doctrine.dbal.default_connection.event_manager'),
215
            [],
216
        ]);
217
218
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
219
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
220
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
221
222
        $this->assertDICConstructorArguments($definition, [
223
            new Reference('doctrine.dbal.default_connection'),
224
            new Reference('doctrine.orm.default_configuration'),
225
        ]);
226
    }
227
228
    /**
229
     * The PDO driver doesn't require a database name to be to set when connecting to a database server
230
     *
231
     * @group legacy
232
     */
233
    public function testLoadSimpleSingleConnectionWithoutDbName()
234
    {
235
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname');
236
237
        /** @var Definition $definition */
238
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
239
240
        $this->assertDICConstructorArguments($definition, [
241
            [
242
                'host' => 'localhost',
243
                'port' => null,
244
                'user' => 'root',
245
                'password' => null,
246
                'driver' => 'pdo_mysql',
247
                'driverOptions' => [],
248
                'defaultTableOptions' => [],
249
            ],
250
            new Reference('doctrine.dbal.default_connection.configuration'),
251
            new Reference('doctrine.dbal.default_connection.event_manager'),
252
            [],
253
        ]);
254
255
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
256
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
257
        $factory = $definition->getFactory();
258
259
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]);
260
        $this->assertEquals('create', $factory[1]);
261
262
        $this->assertDICConstructorArguments($definition, [
263
            new Reference('doctrine.dbal.default_connection'),
264
            new Reference('doctrine.orm.default_configuration'),
265
        ]);
266
    }
267
268
    /**
269
     * @group legacy
270
     */
271
    public function testLoadSingleConnection()
272
    {
273
        $container = $this->loadContainer('orm_service_single_entity_manager');
274
275
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
276
277
        $this->assertDICConstructorArguments($definition, [
278
            [
279
                'host' => 'localhost',
280
                'driver' => 'pdo_sqlite',
281
                'driverOptions' => [],
282
                'user' => 'sqlite_user',
283
                'port' => null,
284
                'password' => 'sqlite_s3cr3t',
285
                'dbname' => 'sqlite_db',
286
                'memory' => true,
287
                'defaultTableOptions' => [],
288
            ],
289
            new Reference('doctrine.dbal.default_connection.configuration'),
290
            new Reference('doctrine.dbal.default_connection.event_manager'),
291
            [],
292
        ]);
293
294
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
295
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
296
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
297
298
        $this->assertDICConstructorArguments($definition, [
299
            new Reference('doctrine.dbal.default_connection'),
300
            new Reference('doctrine.orm.default_configuration'),
301
        ]);
302
303
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
304
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', ['Acme\Doctrine\Repository']);
305
    }
306
307
    /**
308
     * @group legacy
309
     */
310
    public function testLoadMultipleConnections()
311
    {
312
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
313
314
        $definition = $container->getDefinition('doctrine.dbal.conn1_connection');
315
316
        $args = $definition->getArguments();
317
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
318
        $this->assertEquals('localhost', $args[0]['host']);
319
        $this->assertEquals('sqlite_user', $args[0]['user']);
320
        $this->assertEquals('doctrine.dbal.conn1_connection.configuration', (string) $args[1]);
321
        $this->assertEquals('doctrine.dbal.conn1_connection.event_manager', (string) $args[2]);
322
323
        $this->assertEquals('doctrine.orm.em2_entity_manager', (string) $container->getAlias('doctrine.orm.entity_manager'));
324
325
        $definition = $container->getDefinition('doctrine.orm.em1_entity_manager');
326
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
327
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
328
329
        $arguments = $definition->getArguments();
330
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
331
        $this->assertEquals('doctrine.dbal.conn1_connection', (string) $arguments[0]);
332
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
333
        $this->assertEquals('doctrine.orm.em1_configuration', (string) $arguments[1]);
334
335
        $definition = $container->getDefinition('doctrine.dbal.conn2_connection');
336
337
        $args = $definition->getArguments();
338
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
339
        $this->assertEquals('localhost', $args[0]['host']);
340
        $this->assertEquals('sqlite_user', $args[0]['user']);
341
        $this->assertEquals('doctrine.dbal.conn2_connection.configuration', (string) $args[1]);
342
        $this->assertEquals('doctrine.dbal.conn2_connection.event_manager', (string) $args[2]);
343
344
        $definition = $container->getDefinition('doctrine.orm.em2_entity_manager');
345
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
346
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
347
348
        $arguments = $definition->getArguments();
349
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
350
        $this->assertEquals('doctrine.dbal.conn2_connection', (string) $arguments[0]);
351
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
352
        $this->assertEquals('doctrine.orm.em2_configuration', (string) $arguments[1]);
353
354
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
355
        $this->assertEquals('%doctrine_cache.xcache.class%', $definition->getClass());
356
357
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_query_cache'));
358
        $this->assertEquals(DoctrineProvider::class, $definition->getClass());
359
        $arguments = $definition->getArguments();
360
        $this->assertInstanceOf(Reference::class, $arguments[0]);
361
        $this->assertEquals('cache.app', (string) $arguments[0]);
362
363
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_result_cache'));
364
        $this->assertEquals(DoctrineProvider::class, $definition->getClass());
365
        $arguments = $definition->getArguments();
366
        $this->assertInstanceOf(Reference::class, $arguments[0]);
367
        $this->assertEquals('cache.app', (string) $arguments[0]);
368
    }
369
370
    public function testLoadLogging()
371
    {
372
        $container = $this->loadContainer('dbal_logging');
373
374
        $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration');
375
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger')]);
376
377
        $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration');
378
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.profiling.profile')]);
379
380
        $definition = $container->getDefinition('doctrine.dbal.profile_with_backtrace_connection.configuration');
381
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.backtrace.profile_with_backtrace')]);
382
383
        $definition = $container->getDefinition('doctrine.dbal.backtrace_without_profile_connection.configuration');
384
        $this->assertDICDefinitionNoMethodCall($definition, 'setSQLLogger');
385
386
        $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration');
387
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.chain.both')]);
388
    }
389
390
    /**
391
     * @group legacy
392
     */
393
    public function testEntityManagerMetadataCacheDriverConfiguration()
394
    {
395
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
396
397
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
398
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.xcache.class%');
399
400
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em2_metadata_cache'));
401
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.apc.class%');
402
    }
403
404
    /**
405
     * @group legacy
406
     */
407 View Code Duplication
    public function testEntityManagerMemcacheMetadataCacheDriverConfiguration()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
408
    {
409
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
410
411
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
412
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.class%');
413
        $this->assertDICDefinitionMethodCallOnce(
414
            $definition,
415
            'setMemcache',
416
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection')]
417
        );
418
419
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection');
420
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.connection.class%');
421
        $this->assertDICDefinitionMethodCallOnce($definition, 'addServer', [
422
            'localhost',
423
            '11211',
424
        ]);
425
    }
426
427
    /**
428
     * @group legacy
429
     */
430 View Code Duplication
    public function testEntityManagerRedisMetadataCacheDriverConfigurationWithDatabaseKey()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
431
    {
432
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_redis');
433
434
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
435
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.class%');
436
        $this->assertDICDefinitionMethodCallOnce(
437
            $definition,
438
            'setRedis',
439
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection')]
440
        );
441
442
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection');
443
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.connection.class%');
444
        $this->assertDICDefinitionMethodCallOnce($definition, 'connect', ['localhost', '6379']);
445
        $this->assertDICDefinitionMethodCallOnce($definition, 'select', [1]);
446
    }
447
448
    /**
449
     * @group legacy
450
     */
451
    public function testDependencyInjectionImportsOverrideDefaults()
452
    {
453
        $container = $this->loadContainer('orm_imports');
454
455
        $cacheDefinition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
456
        $this->assertEquals('%doctrine_cache.apc.class%', $cacheDefinition->getClass());
457
458
        $configDefinition = $container->getDefinition('doctrine.orm.default_configuration');
459
        $this->assertDICDefinitionMethodCallOnce($configDefinition, 'setAutoGenerateProxyClasses', ['%doctrine.orm.auto_generate_proxy_classes%']);
460
    }
461
462
    public function testSingleEntityManagerMultipleMappingBundleDefinitions()
463
    {
464
        $container = $this->loadContainer('orm_single_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
465
466
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
467
468
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [
469
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
470
            'Fixtures\Bundles\AnnotationsBundle\Entity',
471
        ]);
472
473
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [
474
            new Reference('doctrine.orm.default_yml_metadata_driver'),
475
            'Fixtures\Bundles\YamlBundle\Entity',
476
        ]);
477
478
        $this->assertDICDefinitionMethodCallAt(2, $definition, 'addDriver', [
479
            new Reference('doctrine.orm.default_xml_metadata_driver'),
480
            'Fixtures\Bundles\XmlBundle',
481
        ]);
482
483
        $annDef = $container->getDefinition('doctrine.orm.default_annotation_metadata_driver');
484
        $this->assertDICConstructorArguments($annDef, [
485
            new Reference('doctrine.orm.metadata.annotation_reader'),
486
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
487
        ]);
488
489
        $ymlDef = $container->getDefinition('doctrine.orm.default_yml_metadata_driver');
490
        $this->assertDICConstructorArguments($ymlDef, [
491
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
492
        ]);
493
494
        $xmlDef = $container->getDefinition('doctrine.orm.default_xml_metadata_driver');
495
        $this->assertDICConstructorArguments($xmlDef, [
496
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
497
        ]);
498
    }
499
500
    public function testMultipleEntityManagersMappingBundleDefinitions()
501
    {
502
        $container = $this->loadContainer('orm_multiple_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
503
504
        $this->assertEquals(['em1' => 'doctrine.orm.em1_entity_manager', 'em2' => 'doctrine.orm.em2_entity_manager'], $container->getParameter('doctrine.entity_managers'), 'Set of the existing EntityManagers names is incorrect.');
505
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), 'Set of the existing EntityManagers names is incorrect.');
506
507
        $def1 = $container->getDefinition('doctrine.orm.em1_metadata_driver');
508
        $def2 = $container->getDefinition('doctrine.orm.em2_metadata_driver');
509
510
        $this->assertDICDefinitionMethodCallAt(0, $def1, 'addDriver', [
511
            new Reference('doctrine.orm.em1_annotation_metadata_driver'),
512
            'Fixtures\Bundles\AnnotationsBundle\Entity',
513
        ]);
514
515
        $this->assertDICDefinitionMethodCallAt(0, $def2, 'addDriver', [
516
            new Reference('doctrine.orm.em2_yml_metadata_driver'),
517
            'Fixtures\Bundles\YamlBundle\Entity',
518
        ]);
519
520
        $this->assertDICDefinitionMethodCallAt(1, $def2, 'addDriver', [
521
            new Reference('doctrine.orm.em2_xml_metadata_driver'),
522
            'Fixtures\Bundles\XmlBundle',
523
        ]);
524
525
        $annDef = $container->getDefinition('doctrine.orm.em1_annotation_metadata_driver');
526
        $this->assertDICConstructorArguments($annDef, [
527
            new Reference('doctrine.orm.metadata.annotation_reader'),
528
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
529
        ]);
530
531
        $ymlDef = $container->getDefinition('doctrine.orm.em2_yml_metadata_driver');
532
        $this->assertDICConstructorArguments($ymlDef, [
533
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
534
        ]);
535
536
        $xmlDef = $container->getDefinition('doctrine.orm.em2_xml_metadata_driver');
537
        $this->assertDICConstructorArguments($xmlDef, [
538
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
539
        ]);
540
    }
541
542
    public function testSingleEntityManagerDefaultTableOptions()
543
    {
544
        $container = $this->loadContainer('orm_single_em_default_table_options', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
545
546
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
547
548
        $this->assertArrayHasKey('defaultTableOptions', $param);
549
550
        $defaults = $param['defaultTableOptions'];
551
552
        $this->assertArrayHasKey('charset', $defaults);
553
        $this->assertArrayHasKey('collate', $defaults);
554
        $this->assertArrayHasKey('engine', $defaults);
555
556
        $this->assertEquals('utf8mb4', $defaults['charset']);
557
        $this->assertEquals('utf8mb4_unicode_ci', $defaults['collate']);
558
        $this->assertEquals('InnoDB', $defaults['engine']);
559
    }
560
561
    public function testSetTypes()
562
    {
563
        $container = $this->loadContainer('dbal_types');
564
565
        $this->assertEquals(
566
            ['test' => ['class' => TestType::class, 'commented' => null]],
567
            $container->getParameter('doctrine.dbal.connection_factory.types')
568
        );
569
        $this->assertEquals('%doctrine.dbal.connection_factory.types%', $container->getDefinition('doctrine.dbal.connection_factory')->getArgument(0));
570
    }
571
572
    public function testSetCustomFunctions()
573
    {
574
        $container = $this->loadContainer('orm_functions');
575
576
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
577
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
578
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomNumericFunction', ['test_numeric', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction']);
579
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomDatetimeFunction', ['test_datetime', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction']);
580
    }
581
582 View Code Duplication
    public function testSetNamingStrategy()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
583
    {
584
        $container = $this->loadContainer('orm_namingstrategy');
585
586
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
587
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
588
589
        $this->assertDICDefinitionMethodCallOnce($def1, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.default')]);
590
        $this->assertDICDefinitionMethodCallOnce($def2, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.underscore')]);
591
    }
592
593 View Code Duplication
    public function testSetQuoteStrategy()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
594
    {
595
        $container = $this->loadContainer('orm_quotestrategy');
596
597
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
598
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
599
600
        $this->assertDICDefinitionMethodCallOnce($def1, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.default')]);
601
        $this->assertDICDefinitionMethodCallOnce($def2, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.ansi')]);
602
    }
603
604
    /**
605
     * @group legacy
606
     */
607
    public function testSecondLevelCache()
608
    {
609
        $container = $this->loadContainer('orm_second_level_cache');
610
611
        $this->assertTrue($container->has('doctrine.orm.default_configuration'));
612
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.cache_configuration'));
613
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region_cache_driver'));
614
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.regions_configuration'));
615
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.default_cache_factory'));
616
617
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_chain'));
618
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_statistics'));
619
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger1'));
620
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger2'));
621
622
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_entity_region'));
623
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_service_region'));
624
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_query_region_filelock'));
625
626
        $slcFactoryDef       = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
627
        $myEntityRegionDef   = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_entity_region');
628
        $loggerChainDef      = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_chain');
629
        $loggerStatisticsDef = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_statistics');
630
        $myQueryRegionDef    = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_query_region_filelock');
631
        $cacheDriverDef      = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_second_level_cache.region_cache_driver'));
632
        $configDef           = $container->getDefinition('doctrine.orm.default_configuration');
633
        $myEntityRegionArgs  = $myEntityRegionDef->getArguments();
634
        $myQueryRegionArgs   = $myQueryRegionDef->getArguments();
635
        $slcFactoryArgs      = $slcFactoryDef->getArguments();
636
637
        $this->assertDICDefinitionClass($slcFactoryDef, '%doctrine.orm.second_level_cache.default_cache_factory.class%');
638
        $this->assertDICDefinitionClass($myQueryRegionDef, '%doctrine.orm.second_level_cache.filelock_region.class%');
639
        $this->assertDICDefinitionClass($myEntityRegionDef, '%doctrine.orm.second_level_cache.default_region.class%');
640
        $this->assertDICDefinitionClass($loggerChainDef, '%doctrine.orm.second_level_cache.logger_chain.class%');
641
        $this->assertDICDefinitionClass($loggerStatisticsDef, '%doctrine.orm.second_level_cache.logger_statistics.class%');
642
        $this->assertDICDefinitionClass($cacheDriverDef, '%doctrine_cache.array.class%');
643
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setSecondLevelCacheConfiguration');
644
        $this->assertDICDefinitionMethodCallCount($slcFactoryDef, 'setRegion', [], 3);
645
        $this->assertDICDefinitionMethodCallCount($loggerChainDef, 'setLogger', [], 3);
646
647
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[0]);
648
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[1]);
649
650
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myEntityRegionArgs[1]);
651
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myQueryRegionArgs[0]);
652
653
        $this->assertEquals('my_entity_region', $myEntityRegionArgs[0]);
654
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_entity_region_driver', $myEntityRegionArgs[1]);
655
        $this->assertEquals(600, $myEntityRegionArgs[2]);
656
657
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_query_region', $myQueryRegionArgs[0]);
658
        $this->assertContains('/doctrine/orm/slc/filelock', $myQueryRegionArgs[1]);
659
        $this->assertEquals(60, $myQueryRegionArgs[2]);
660
661
        $this->assertEquals('doctrine.orm.default_second_level_cache.regions_configuration', $slcFactoryArgs[0]);
662
        $this->assertEquals('doctrine.orm.default_second_level_cache.region_cache_driver', $slcFactoryArgs[1]);
663
    }
664
665
    public function testSingleEMSetCustomFunctions()
666
    {
667
        $container = $this->loadContainer('orm_single_em_dql_functions');
668
669
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
670
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
671
    }
672
673
    public function testAddCustomHydrationMode()
674
    {
675
        $container = $this->loadContainer('orm_hydration_mode');
676
677
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
678
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomHydrationMode', ['test_hydrator', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator']);
679
    }
680
681
    public function testAddFilter()
682
    {
683
        $container = $this->loadContainer('orm_filters');
684
685
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
686
        $args       = [
687
            ['soft_delete', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
688
            ['myFilter', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
689
        ];
690
        $this->assertDICDefinitionMethodCallCount($definition, 'addFilter', $args, 2);
691
692
        $definition = $container->getDefinition('doctrine.orm.default_manager_configurator');
693
        $this->assertDICConstructorArguments($definition, [['soft_delete', 'myFilter'], ['myFilter' => ['myParameter' => 'myValue', 'mySecondParameter' => 'mySecondValue']]]);
694
695
        // Let's create the instance to check the configurator work.
696
        /** @var EntityManager $entityManager */
697
        $entityManager = $container->get('doctrine.orm.entity_manager');
698
        $this->assertCount(2, $entityManager->getFilters()->getEnabledFilters());
0 ignored issues
show
Documentation introduced by
$entityManager->getFilters()->getEnabledFilters() is of type array<integer,object<Doc...uery\Filter\SQLFilter>>, but the function expects a object<Countable>|object...nit\Framework\iterable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
699
    }
700
701
    public function testResolveTargetEntity()
702
    {
703
        $container = $this->loadContainer('orm_resolve_target_entity');
704
705
        $definition = $container->getDefinition('doctrine.orm.listeners.resolve_target_entity');
706
        $this->assertDICDefinitionMethodCallOnce($definition, 'addResolveTargetEntity', ['Symfony\Component\Security\Core\User\UserInterface', 'MyUserClass', []]);
707
708
        $this->assertEquals(['doctrine.event_subscriber' => [[]]], $definition->getTags());
709
    }
710
711
    public function testAttachEntityListeners()
712
    {
713
        $container = $this->loadContainer('orm_attach_entity_listener');
714
715
        $definition  = $container->getDefinition('doctrine.orm.default_listeners.attach_entity_listeners');
716
        $methodCalls = $definition->getMethodCalls();
717
718
        $this->assertDICDefinitionMethodCallCount($definition, 'addEntityListener', [], 6);
719
        $this->assertEquals(['doctrine.event_listener' => [ ['event' => 'loadClassMetadata'] ] ], $definition->getTags());
720
721
        $this->assertEquals($methodCalls[0], [
722
            'addEntityListener',
723
            [
724
                'ExternalBundles\Entities\FooEntity',
725
                'MyBundles\Listeners\FooEntityListener',
726
                'prePersist',
727
                null,
728
            ],
729
        ]);
730
731
        $this->assertEquals($methodCalls[1], [
732
            'addEntityListener',
733
            [
734
                'ExternalBundles\Entities\FooEntity',
735
                'MyBundles\Listeners\FooEntityListener',
736
                'postPersist',
737
                'postPersist',
738
            ],
739
        ]);
740
741
        $this->assertEquals($methodCalls[2], [
742
            'addEntityListener',
743
            [
744
                'ExternalBundles\Entities\FooEntity',
745
                'MyBundles\Listeners\FooEntityListener',
746
                'postLoad',
747
                'postLoadHandler',
748
            ],
749
        ]);
750
751
        $this->assertEquals($methodCalls[3], [
752
            'addEntityListener',
753
            [
754
                'ExternalBundles\Entities\BarEntity',
755
                'MyBundles\Listeners\BarEntityListener',
756
                'prePersist',
757
                'prePersist',
758
            ],
759
        ]);
760
761
        $this->assertEquals($methodCalls[4], [
762
            'addEntityListener',
763
            [
764
                'ExternalBundles\Entities\BarEntity',
765
                'MyBundles\Listeners\BarEntityListener',
766
                'prePersist',
767
                'prePersistHandler',
768
            ],
769
        ]);
770
771
        $this->assertEquals($methodCalls[5], [
772
            'addEntityListener',
773
            [
774
                'ExternalBundles\Entities\BarEntity',
775
                'MyBundles\Listeners\LogDeleteEntityListener',
776
                'postDelete',
777
                'postDelete',
778
            ],
779
        ]);
780
    }
781
782
    public function testDbalAutoCommit()
783
    {
784
        $container = $this->loadContainer('dbal_auto_commit');
785
786
        $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration');
787
        $this->assertDICDefinitionMethodCallOnce($definition, 'setAutoCommit', [false]);
788
    }
789
790
    public function testDbalOracleConnectstring()
791
    {
792
        $container = $this->loadContainer('dbal_oracle_connectstring');
793
794
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
795
        $this->assertSame('scott@sales-server:1521/sales.us.example.com', $config['connectstring']);
796
    }
797
798
    public function testDbalOracleInstancename()
799
    {
800
        $container = $this->loadContainer('dbal_oracle_instancename');
801
802
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
803
        $this->assertSame('mySuperInstance', $config['instancename']);
804
    }
805
806
    public function testDbalSchemaFilter()
807
    {
808
        if (method_exists(Configuration::class, 'setSchemaAssetsFilter')) {
809
            $this->markTestSkipped('Test only applies to doctrine/dbal 2.8 or lower');
810
        }
811
812
        $container = $this->loadContainer('dbal_schema_filter');
813
814
        $definition = $container->getDefinition('doctrine.dbal.connection1_connection.configuration');
815
        $this->assertDICDefinitionMethodCallOnce($definition, 'setFilterSchemaAssetsExpression', ['~^(?!t_)~']);
816
    }
817
818
    public function testDbalSchemaFilterNewConfig()
819
    {
820
        if (! method_exists(Configuration::class, 'setSchemaAssetsFilter')) {
821
            $this->markTestSkipped('Test requires doctrine/dbal 2.9 or higher');
822
        }
823
824
        $container = $this->getContainer([]);
825
        $loader    = new DoctrineExtension();
826
        $container->registerExtension($loader);
827
        $container->addCompilerPass(new DbalSchemaFilterPass());
828
829
        // ignore table1 table on "default" connection
830
        $container->register('dummy_filter1', DummySchemaAssetsFilter::class)
831
            ->setArguments(['table1'])
832
            ->addTag('doctrine.dbal.schema_filter');
833
834
        // ignore table2 table on "connection2" connection
835
        $container->register('dummy_filter2', DummySchemaAssetsFilter::class)
836
            ->setArguments(['table2'])
837
            ->addTag('doctrine.dbal.schema_filter', ['connection' => 'connection2']);
838
839
        $this->loadFromFile($container, 'dbal_schema_filter');
840
841
        $assetNames               = ['table1', 'table2', 'table3', 't_ignored'];
842
        $expectedConnectionAssets = [
843
            // ignores table1 + schema_filter applies
844
            'connection1' => ['table2', 'table3'],
845
            // ignores table2, no schema_filter applies
846
            'connection2' => ['table1', 'table3', 't_ignored'],
847
            // connection3 has no ignores, handled separately
848
        ];
849
850
        $this->compileContainer($container);
851
852
        $getConfiguration = static function (string $connectionName) use ($container) : Configuration {
853
            return $container->get(sprintf('doctrine.dbal.%s_connection', $connectionName))->getConfiguration();
854
        };
855
856
        foreach ($expectedConnectionAssets as $connectionName => $expectedTables) {
857
            $connConfig = $getConfiguration($connectionName);
858
            $this->assertSame($expectedTables, array_values(array_filter($assetNames, $connConfig->getSchemaAssetsFilter())), sprintf('Filtering for connection "%s"', $connectionName));
859
        }
860
861
        $this->assertNull($connConfig = $getConfiguration('connection3')->getSchemaAssetsFilter());
862
    }
863
864
    public function testEntityListenerResolver()
865
    {
866
        $container = $this->loadContainer('orm_entity_listener_resolver', ['YamlBundle'], new EntityListenerPass());
867
868
        $definition = $container->getDefinition('doctrine.orm.em1_configuration');
869
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em1_entity_listener_resolver')]);
870
871
        $definition = $container->getDefinition('doctrine.orm.em2_configuration');
872
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em2_entity_listener_resolver')]);
873
874
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
875
        $this->assertDICDefinitionMethodCallOnce($listener, 'registerService', ['EntityListener', 'entity_listener1']);
876
877
        $listener = $container->getDefinition('entity_listener_resolver');
878
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]);
879
    }
880
881
    public function testAttachEntityListenerTag()
882
    {
883
        $container = $this->getContainer([]);
884
        $loader    = new DoctrineExtension();
885
        $container->registerExtension($loader);
886
        $container->addCompilerPass(new EntityListenerPass());
887
888
        $this->loadFromFile($container, 'orm_attach_entity_listener_tag');
889
890
        $this->compileContainer($container);
891
892
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
893
        $this->assertDICDefinitionMethodCallOnce($listener, 'registerService', ['EntityListener1', 'entity_listener1']);
894
895
        $listener = $container->getDefinition('doctrine.orm.em2_entity_listener_resolver');
896
        $this->assertDICDefinitionMethodCallOnce($listener, 'registerService', ['EntityListener2', 'entity_listener2']);
897
898
        $attachListener = $container->getDefinition('doctrine.orm.em1_listeners.attach_entity_listeners');
899
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity1', 'EntityListener1', 'postLoad']);
900
901
        $attachListener = $container->getDefinition('doctrine.orm.em2_listeners.attach_entity_listeners');
902
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity2', 'EntityListener2', 'preFlush', 'preFlushHandler']);
903
    }
904
905
    public function testAttachEntityListenersTwoConnections()
906
    {
907
        $container = $this->getContainer(['YamlBundle']);
908
        $loader    = new DoctrineExtension();
909
        $container->registerExtension($loader);
910
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'));
911
912
        $this->loadFromFile($container, 'orm_attach_entity_listeners_two_connections');
913
914
        $this->compileContainer($container);
915
916
        $defaultEventManager = $container->getDefinition('doctrine.dbal.default_connection.event_manager');
917
        $this->assertDICDefinitionNoMethodCall($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
918
        $this->assertDICDefinitionMethodCallOnce($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
919
920
        $foobarEventManager = $container->getDefinition('doctrine.dbal.foobar_connection.event_manager');
921
        $this->assertDICDefinitionNoMethodCall($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
922
        $this->assertDICDefinitionMethodCallOnce($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
923
    }
924
925
    public function testAttachLazyEntityListener()
926
    {
927
        $container = $this->getContainer([]);
928
        $loader    = new DoctrineExtension();
929
        $container->registerExtension($loader);
930
        $container->addCompilerPass(new EntityListenerPass());
931
932
        $this->loadFromFile($container, 'orm_attach_lazy_entity_listener');
933
934
        $this->compileContainer($container);
935
936
        $resolver1 = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
937
        $this->assertDICDefinitionMethodCallAt(0, $resolver1, 'registerService', ['EntityListener1', 'entity_listener1']);
938
        $this->assertDICDefinitionMethodCallAt(1, $resolver1, 'register', [new Reference('entity_listener3')]);
939
        $this->assertDICDefinitionMethodCallAt(2, $resolver1, 'registerService', ['EntityListener4', 'entity_listener4']);
940
941
        $serviceLocatorReference = $resolver1->getArgument(0);
942
        $this->assertInstanceOf(Reference::class, $serviceLocatorReference);
943
        $serviceLocatorDefinition = $container->getDefinition((string) $serviceLocatorReference);
944
        $this->assertSame(ServiceLocator::class, $serviceLocatorDefinition->getClass());
945
        $serviceLocatorMap = $serviceLocatorDefinition->getArgument(0);
946
        $this->assertSame(['entity_listener1', 'entity_listener4'], array_keys($serviceLocatorMap));
947
948
        $resolver2 = $container->findDefinition('custom_entity_listener_resolver');
949
        $this->assertDICDefinitionMethodCallOnce($resolver2, 'registerService', ['EntityListener2', 'entity_listener2']);
950
    }
951
952
    public function testAttachLazyEntityListenerForCustomResolver()
953
    {
954
        $container = $this->getContainer([]);
955
        $loader    = new DoctrineExtension();
956
        $container->registerExtension($loader);
957
        $container->addCompilerPass(new EntityListenerPass());
958
959
        $this->loadFromFile($container, 'orm_entity_listener_custom_resolver');
960
961
        $this->compileContainer($container);
962
963
        $resolver = $container->getDefinition('custom_entity_listener_resolver');
964
        $this->assertTrue($resolver->isPublic());
965
        $this->assertEmpty($resolver->getArguments(), 'We must not change the arguments for custom services.');
966
        $this->assertDICDefinitionMethodCallOnce($resolver, 'registerService', ['EntityListener', 'entity_listener']);
967
        $this->assertTrue($container->getDefinition('entity_listener')->isPublic());
968
    }
969
970
    /**
971
     * @expectedException \InvalidArgumentException
972
     * @expectedExceptionMessage EntityListenerServiceResolver
973
     */
974 View Code Duplication
    public function testLazyEntityListenerResolverWithoutCorrectInterface()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
975
    {
976
        $container = $this->getContainer([]);
977
        $loader    = new DoctrineExtension();
978
        $container->registerExtension($loader);
979
        $container->addCompilerPass(new EntityListenerPass());
980
981
        $this->loadFromFile($container, 'orm_entity_listener_lazy_resolver_without_interface');
982
983
        $this->compileContainer($container);
984
    }
985
986
    public function testPrivateLazyEntityListener()
987
    {
988
        $container = $this->getContainer([]);
989
        $loader    = new DoctrineExtension();
990
        $container->registerExtension($loader);
991
        $container->addCompilerPass(new EntityListenerPass());
992
993
        $this->loadFromFile($container, 'orm_entity_listener_lazy_private');
994
995
        $this->compileContainer($container);
996
997
        $this->assertTrue($container->getDefinition('doctrine.orm.em1_entity_listener_resolver')->isPublic());
998
    }
999
1000
    /**
1001
     * @expectedException \InvalidArgumentException
1002
     * @expectedExceptionMessageRegExp /The service ".*" must not be abstract as this entity listener is lazy-loaded/
1003
     */
1004 View Code Duplication
    public function testAbstractLazyEntityListener()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1005
    {
1006
        $container = $this->getContainer([]);
1007
        $loader    = new DoctrineExtension();
1008
        $container->registerExtension($loader);
1009
        $container->addCompilerPass(new EntityListenerPass());
1010
1011
        $this->loadFromFile($container, 'orm_entity_listener_lazy_abstract');
1012
1013
        $this->compileContainer($container);
1014
    }
1015
1016
    public function testRepositoryFactory()
1017
    {
1018
        $container = $this->loadContainer('orm_repository_factory');
1019
1020
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
1021
        $this->assertDICDefinitionMethodCallOnce($definition, 'setRepositoryFactory', ['repository_factory']);
1022
    }
1023
1024
    private function loadContainer($fixture, array $bundles = ['YamlBundle'], CompilerPassInterface $compilerPass = null)
1025
    {
1026
        $container = $this->getContainer($bundles);
1027
        $extension = new FrameworkExtension();
1028
        $container->registerExtension($extension);
1029
        $extension->load(['framework' => []], $container);
1030
1031
        $container->registerExtension(new DoctrineExtension());
1032
1033
        $this->loadFromFile($container, $fixture);
1034
1035
        if ($compilerPass !== null) {
1036
            $container->addCompilerPass($compilerPass);
1037
        }
1038
1039
        $this->compileContainer($container);
1040
1041
        return $container;
1042
    }
1043
1044
    private function getContainer(array $bundles)
1045
    {
1046
        $map = [];
1047
        foreach ($bundles as $bundle) {
1048
            require_once __DIR__ . '/Fixtures/Bundles/' . $bundle . '/' . $bundle . '.php';
1049
1050
            $map[$bundle] = 'Fixtures\\Bundles\\' . $bundle . '\\' . $bundle;
1051
        }
1052
1053
        return new ContainerBuilder(new ParameterBag([
1054
            'kernel.name' => 'app',
1055
            'kernel.debug' => false,
1056
            'kernel.bundles' => $map,
1057
            'kernel.cache_dir' => sys_get_temp_dir(),
1058
            'kernel.environment' => 'test',
1059
            'kernel.root_dir' => __DIR__ . '/../../', // src dir
1060
            'kernel.project_dir' => __DIR__ . '/../../', // src dir
1061
            'kernel.bundles_metadata' => [],
1062
            'container.build_id' => uniqid(),
1063
        ]));
1064
    }
1065
1066
    /**
1067
     * Assertion on the Class of a DIC Service Definition.
1068
     *
1069
     * @param string $expectedClass
1070
     */
1071
    private function assertDICDefinitionClass(Definition $definition, $expectedClass)
1072
    {
1073
        $this->assertEquals($expectedClass, $definition->getClass(), 'Expected Class of the DIC Container Service Definition is wrong.');
1074
    }
1075
1076
    private function assertDICConstructorArguments(Definition $definition, $args)
1077
    {
1078
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match.");
1079
    }
1080
1081 View Code Duplication
    private function assertDICDefinitionMethodCallAt($pos, Definition $definition, $methodName, array $params = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1082
    {
1083
        $calls = $definition->getMethodCalls();
1084
        if (! isset($calls[$pos][0])) {
1085
            $this->fail(sprintf('Method call at position %s not found!', $pos));
1086
1087
            return;
1088
        }
1089
1090
        $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.');
1091
1092
        if ($params === null) {
1093
            return;
1094
        }
1095
1096
        $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1097
    }
1098
1099
    /**
1100
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
1101
     *
1102
     * @param string $methodName
1103
     * @param array  $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be null|array?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1104
     */
1105 View Code Duplication
    private function assertDICDefinitionMethodCallOnce(Definition $definition, $methodName, array $params = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1106
    {
1107
        $calls  = $definition->getMethodCalls();
1108
        $called = false;
1109
        foreach ($calls as $call) {
1110
            if ($call[0] !== $methodName) {
1111
                continue;
1112
            }
1113
1114
            if ($called) {
1115
                $this->fail("Method '" . $methodName . "' is expected to be called only once, a second call was registered though.");
1116
            } else {
1117
                $called = true;
1118
                if ($params !== null) {
1119
                    $this->assertEquals($params, $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1120
                }
1121
            }
1122
        }
1123
        if ($called) {
1124
            return;
1125
        }
1126
1127
        $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though.");
1128
    }
1129
1130
    private function assertDICDefinitionMethodCallCount(Definition $definition, $methodName, array $params = [], $nbCalls = 1)
1131
    {
1132
        $calls  = $definition->getMethodCalls();
1133
        $called = 0;
1134
        foreach ($calls as $call) {
1135
            if ($call[0] !== $methodName) {
1136
                continue;
1137
            }
1138
1139
            if ($called > $nbCalls) {
1140
                break;
1141
            }
1142
1143
            if (isset($params[$called])) {
1144
                $this->assertEquals($params[$called], $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1145
            }
1146
            $called++;
1147
        }
1148
1149
        $this->assertEquals($nbCalls, $called, sprintf('The method "%s" should be called %d times', $methodName, $nbCalls));
1150
    }
1151
1152
    /**
1153
     * Assertion for the DI Container, check if the given definition does not contain a method call with the given parameters.
1154
     *
1155
     * @param string $methodName
1156
     * @param array  $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be null|array?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1157
     */
1158
    private function assertDICDefinitionNoMethodCall(Definition $definition, $methodName, array $params = null)
1159
    {
1160
        $calls = $definition->getMethodCalls();
1161
        foreach ($calls as $call) {
1162
            if ($call[0] !== $methodName) {
1163
                continue;
1164
            }
1165
1166
            if ($params !== null) {
1167
                $this->assertNotEquals($params, $call[1], "Method '" . $methodName . "' is not expected to be called with the given parameters.");
1168
            } else {
1169
                $this->fail("Method '" . $methodName . "' is not expected to be called");
1170
            }
1171
        }
1172
    }
1173
1174
    private function compileContainer(ContainerBuilder $container)
1175
    {
1176
        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
1177
        $container->getCompilerPassConfig()->setRemovingPasses([]);
1178
        $container->compile();
1179
    }
1180
}
1181
1182
class DummySchemaAssetsFilter
1183
{
1184
    /** @var string */
1185
    private $tableToIgnore;
1186
1187
    public function __construct(string $tableToIgnore)
1188
    {
1189
        $this->tableToIgnore = $tableToIgnore;
1190
    }
1191
1192
    public function __invoke($assetName) : bool
1193
    {
1194
        if ($assetName instanceof AbstractAsset) {
1195
            $assetName = $assetName->getName();
1196
        }
1197
1198
        return $assetName !== $this->tableToIgnore;
1199
    }
1200
}
1201