Completed
Push — master ( 4725c6...ad278e )
by Andreas
22s
created

testLoadMultipleConnections()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 53

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 53
rs 9.0254
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\EntityListenerPass;
6
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
7
use Doctrine\ORM\EntityManager;
8
use PHPUnit\Framework\TestCase;
9
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
10
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
11
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
12
use Symfony\Component\DependencyInjection\ContainerBuilder;
13
use Symfony\Component\DependencyInjection\Definition;
14
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
15
use Symfony\Component\DependencyInjection\Reference;
16
17
abstract class AbstractDoctrineExtensionTest extends TestCase
18
{
19
    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...
20
21
    public function testDbalLoadFromXmlMultipleConnections()
22
    {
23
        $container = $this->loadContainer('dbal_service_multiple_connections');
24
25
        // doctrine.dbal.mysql_connection
26
        $config = $container->getDefinition('doctrine.dbal.mysql_connection')->getArgument(0);
27
28
        $this->assertEquals('mysql_s3cr3t', $config['password']);
29
        $this->assertEquals('mysql_user', $config['user']);
30
        $this->assertEquals('mysql_db', $config['dbname']);
31
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
32
33
        // doctrine.dbal.sqlite_connection
34
        $config = $container->getDefinition('doctrine.dbal.sqlite_connection')->getArgument(0);
35
        $this->assertSame('pdo_sqlite', $config['driver']);
36
        $this->assertSame('sqlite_db', $config['dbname']);
37
        $this->assertSame('sqlite_user', $config['user']);
38
        $this->assertSame('sqlite_s3cr3t', $config['password']);
39
        $this->assertSame('/tmp/db.sqlite', $config['path']);
40
        $this->assertTrue($config['memory']);
41
42
        // doctrine.dbal.oci8_connection
43
        $config = $container->getDefinition('doctrine.dbal.oci_connection')->getArgument(0);
44
        $this->assertSame('oci8', $config['driver']);
45
        $this->assertSame('oracle_db', $config['dbname']);
46
        $this->assertSame('oracle_user', $config['user']);
47
        $this->assertSame('oracle_s3cr3t', $config['password']);
48
        $this->assertSame('oracle_service', $config['servicename']);
49
        $this->assertTrue($config['service']);
50
        $this->assertTrue($config['pooled']);
51
        $this->assertSame('utf8', $config['charset']);
52
53
        // doctrine.dbal.ibmdb2_connection
54
        $config = $container->getDefinition('doctrine.dbal.ibmdb2_connection')->getArgument(0);
55
        $this->assertSame('ibm_db2', $config['driver']);
56
        $this->assertSame('ibmdb2_db', $config['dbname']);
57
        $this->assertSame('ibmdb2_user', $config['user']);
58
        $this->assertSame('ibmdb2_s3cr3t', $config['password']);
59
        $this->assertSame('TCPIP', $config['protocol']);
60
61
        // doctrine.dbal.pgsql_connection
62
        $config = $container->getDefinition('doctrine.dbal.pgsql_connection')->getArgument(0);
63
        $this->assertSame('pdo_pgsql', $config['driver']);
64
        $this->assertSame('pgsql_schema', $config['dbname']);
65
        $this->assertSame('pgsql_user', $config['user']);
66
        $this->assertSame('pgsql_s3cr3t', $config['password']);
67
        $this->assertSame('pgsql_db', $config['default_dbname']);
68
        $this->assertSame('require', $config['sslmode']);
69
        $this->assertSame('postgresql-ca.pem', $config['sslrootcert']);
70
        $this->assertSame('postgresql-cert.pem', $config['sslcert']);
71
        $this->assertSame('postgresql-key.pem', $config['sslkey']);
72
        $this->assertSame('postgresql.crl', $config['sslcrl']);
73
        $this->assertSame('utf8', $config['charset']);
74
75
        // doctrine.dbal.sqlanywhere_connection
76
        $config = $container->getDefinition('doctrine.dbal.sqlanywhere_connection')->getArgument(0);
77
        $this->assertSame('sqlanywhere', $config['driver']);
78
        $this->assertSame('localhost', $config['host']);
79
        $this->assertSame(2683, $config['port']);
80
        $this->assertSame('sqlanywhere_server', $config['server']);
81
        $this->assertSame('sqlanywhere_db', $config['dbname']);
82
        $this->assertSame('sqlanywhere_user', $config['user']);
83
        $this->assertSame('sqlanywhere_s3cr3t', $config['password']);
84
        $this->assertTrue($config['persistent']);
85
        $this->assertSame('utf8', $config['charset']);
86
    }
87
88
    public function testDbalLoadFromXmlSingleConnections()
89
    {
90
        $container = $this->loadContainer('dbal_service_single_connection');
91
92
        // doctrine.dbal.mysql_connection
93
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
94
95
        $this->assertEquals('mysql_s3cr3t', $config['password']);
96
        $this->assertEquals('mysql_user', $config['user']);
97
        $this->assertEquals('mysql_db', $config['dbname']);
98
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
99
        $this->assertEquals('5.6.20', $config['serverVersion']);
100
    }
101
102
    public function testDbalLoadSingleMasterSlaveConnection()
103
    {
104
        $container = $this->loadContainer('dbal_service_single_master_slave_connection');
105
106
        // doctrine.dbal.mysql_connection
107
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
108
109
        $this->assertEquals('Doctrine\\DBAL\\Connections\\MasterSlaveConnection', $param['wrapperClass']);
110
        $this->assertTrue($param['keepSlave']);
111
        $this->assertEquals(
112
            [
113
                'user' => 'mysql_user',
114
                'password' => 'mysql_s3cr3t',
115
                'port' => null,
116
                'dbname' => 'mysql_db',
117
                'host' => 'localhost',
118
                'unix_socket' => '/path/to/mysqld.sock',
119
                'defaultTableOptions' => [],
120
            ],
121
            $param['master']
122
        );
123
        $this->assertEquals(
124
            [
125
                'user' => 'slave_user',
126
                'password' => 'slave_s3cr3t',
127
                'port' => null,
128
                'dbname' => 'slave_db',
129
                'host' => 'localhost',
130
                'unix_socket' => '/path/to/mysqld_slave.sock',
131
            ],
132
            $param['slaves']['slave1']
133
        );
134
    }
135
136
    public function testDbalLoadPoolShardingConnection()
137
    {
138
        $container = $this->loadContainer('dbal_service_pool_sharding_connection');
139
140
        // doctrine.dbal.mysql_connection
141
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
142
143
        $this->assertEquals('Doctrine\\DBAL\\Sharding\\PoolingShardConnection', $param['wrapperClass']);
144
        $this->assertEquals(new Reference('foo.shard_choser'), $param['shardChoser']);
145
        $this->assertEquals(
146
            [
147
                'user' => 'mysql_user',
148
                'password' => 'mysql_s3cr3t',
149
                'port' => null,
150
                'dbname' => 'mysql_db',
151
                'host' => 'localhost',
152
                'unix_socket' => '/path/to/mysqld.sock',
153
                'defaultTableOptions' => [],
154
            ],
155
            $param['global']
156
        );
157
        $this->assertEquals(
158
            [
159
                'user' => 'shard_user',
160
                'password' => 'shard_s3cr3t',
161
                'port' => null,
162
                'dbname' => 'shard_db',
163
                'host' => 'localhost',
164
                'unix_socket' => '/path/to/mysqld_shard.sock',
165
                'id' => 1,
166
            ],
167
            $param['shards'][0]
168
        );
169
    }
170
171
    public function testDbalLoadSavepointsForNestedTransactions()
172
    {
173
        $container = $this->loadContainer('dbal_savepoints');
174
175
        $calls = $container->getDefinition('doctrine.dbal.savepoints_connection')->getMethodCalls();
176
        $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...
177
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
178
        $this->assertTrue($calls[0][1][0]);
179
180
        $calls = $container->getDefinition('doctrine.dbal.nosavepoints_connection')->getMethodCalls();
181
        $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...
182
183
        $calls = $container->getDefinition('doctrine.dbal.notset_connection')->getMethodCalls();
184
        $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...
185
    }
186
187
    public function testLoadSimpleSingleConnection()
188
    {
189
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
190
191
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
192
193
        $this->assertDICConstructorArguments($definition, [
194
            [
195
                'dbname' => 'db',
196
                'host' => 'localhost',
197
                'port' => null,
198
                'user' => 'root',
199
                'password' => null,
200
                'driver' => 'pdo_mysql',
201
                'driverOptions' => [],
202
                'defaultTableOptions' => [],
203
            ],
204
            new Reference('doctrine.dbal.default_connection.configuration'),
205
            new Reference('doctrine.dbal.default_connection.event_manager'),
206
            [],
207
        ]);
208
209
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
210
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
211
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
212
213
        $this->assertDICConstructorArguments($definition, [
214
            new Reference('doctrine.dbal.default_connection'),
215
            new Reference('doctrine.orm.default_configuration'),
216
        ]);
217
    }
218
219
    /**
220
     * The PDO driver doesn't require a database name to be to set when connecting to a database server
221
     */
222
    public function testLoadSimpleSingleConnectionWithoutDbName()
223
    {
224
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname');
225
226
        /** @var Definition $definition */
227
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
228
229
        $this->assertDICConstructorArguments($definition, [
230
            [
231
                'host' => 'localhost',
232
                'port' => null,
233
                'user' => 'root',
234
                'password' => null,
235
                'driver' => 'pdo_mysql',
236
                'driverOptions' => [],
237
                'defaultTableOptions' => [],
238
            ],
239
            new Reference('doctrine.dbal.default_connection.configuration'),
240
            new Reference('doctrine.dbal.default_connection.event_manager'),
241
            [],
242
        ]);
243
244
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
245
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
246
        $factory = $definition->getFactory();
247
248
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]);
249
        $this->assertEquals('create', $factory[1]);
250
251
        $this->assertDICConstructorArguments($definition, [
252
            new Reference('doctrine.dbal.default_connection'),
253
            new Reference('doctrine.orm.default_configuration'),
254
        ]);
255
    }
256
257
    public function testLoadSingleConnection()
258
    {
259
        $container = $this->loadContainer('orm_service_single_entity_manager');
260
261
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
262
263
        $this->assertDICConstructorArguments($definition, [
264
            [
265
                'host' => 'localhost',
266
                'driver' => 'pdo_sqlite',
267
                'driverOptions' => [],
268
                'user' => 'sqlite_user',
269
                'port' => null,
270
                'password' => 'sqlite_s3cr3t',
271
                'dbname' => 'sqlite_db',
272
                'memory' => true,
273
                'defaultTableOptions' => [],
274
            ],
275
            new Reference('doctrine.dbal.default_connection.configuration'),
276
            new Reference('doctrine.dbal.default_connection.event_manager'),
277
            [],
278
        ]);
279
280
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
281
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
282
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
283
284
        $this->assertDICConstructorArguments($definition, [
285
            new Reference('doctrine.dbal.default_connection'),
286
            new Reference('doctrine.orm.default_configuration'),
287
        ]);
288
289
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
290
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', ['Acme\Doctrine\Repository']);
291
    }
292
293
    public function testLoadMultipleConnections()
294
    {
295
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
296
297
        $definition = $container->getDefinition('doctrine.dbal.conn1_connection');
298
299
        $args = $definition->getArguments();
300
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
301
        $this->assertEquals('localhost', $args[0]['host']);
302
        $this->assertEquals('sqlite_user', $args[0]['user']);
303
        $this->assertEquals('doctrine.dbal.conn1_connection.configuration', (string) $args[1]);
304
        $this->assertEquals('doctrine.dbal.conn1_connection.event_manager', (string) $args[2]);
305
306
        $this->assertEquals('doctrine.orm.em2_entity_manager', (string) $container->getAlias('doctrine.orm.entity_manager'));
307
308
        $definition = $container->getDefinition('doctrine.orm.em1_entity_manager');
309
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
310
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
311
312
        $arguments = $definition->getArguments();
313
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
314
        $this->assertEquals('doctrine.dbal.conn1_connection', (string) $arguments[0]);
315
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
316
        $this->assertEquals('doctrine.orm.em1_configuration', (string) $arguments[1]);
317
318
        $definition = $container->getDefinition('doctrine.dbal.conn2_connection');
319
320
        $args = $definition->getArguments();
321
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
322
        $this->assertEquals('localhost', $args[0]['host']);
323
        $this->assertEquals('sqlite_user', $args[0]['user']);
324
        $this->assertEquals('doctrine.dbal.conn2_connection.configuration', (string) $args[1]);
325
        $this->assertEquals('doctrine.dbal.conn2_connection.event_manager', (string) $args[2]);
326
327
        $definition = $container->getDefinition('doctrine.orm.em2_entity_manager');
328
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
329
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
330
331
        $arguments = $definition->getArguments();
332
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
333
        $this->assertEquals('doctrine.dbal.conn2_connection', (string) $arguments[0]);
334
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
335
        $this->assertEquals('doctrine.orm.em2_configuration', (string) $arguments[1]);
336
337
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
338
        $this->assertEquals('%doctrine_cache.xcache.class%', $definition->getClass());
339
340
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_query_cache'));
341
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
342
343
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_result_cache'));
344
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
345
    }
346
347
    public function testLoadLogging()
348
    {
349
        $container = $this->loadContainer('dbal_logging');
350
351
        $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration');
352
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger')]);
353
354
        $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration');
355
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.profiling.profile')]);
356
357
        $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration');
358
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.chain.both')]);
359
    }
360
361
    public function testEntityManagerMetadataCacheDriverConfiguration()
362
    {
363
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
364
365
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
366
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.xcache.class%');
367
368
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em2_metadata_cache'));
369
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.apc.class%');
370
    }
371
372 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...
373
    {
374
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
375
376
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
377
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.class%');
378
        $this->assertDICDefinitionMethodCallOnce(
379
            $definition,
380
            'setMemcache',
381
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection')]
382
        );
383
384
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection');
385
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.connection.class%');
386
        $this->assertDICDefinitionMethodCallOnce($definition, 'addServer', [
387
            'localhost',
388
            '11211',
389
        ]);
390
    }
391
392 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...
393
    {
394
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_redis');
395
396
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
397
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.class%');
398
        $this->assertDICDefinitionMethodCallOnce(
399
            $definition,
400
            'setRedis',
401
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection')]
402
        );
403
404
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection');
405
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.connection.class%');
406
        $this->assertDICDefinitionMethodCallOnce($definition, 'connect', ['localhost', '6379']);
407
        $this->assertDICDefinitionMethodCallOnce($definition, 'select', [1]);
408
    }
409
410
    public function testDependencyInjectionImportsOverrideDefaults()
411
    {
412
        $container = $this->loadContainer('orm_imports');
413
414
        $cacheDefinition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
415
        $this->assertEquals('%doctrine_cache.apc.class%', $cacheDefinition->getClass());
416
417
        $configDefinition = $container->getDefinition('doctrine.orm.default_configuration');
418
        $this->assertDICDefinitionMethodCallOnce($configDefinition, 'setAutoGenerateProxyClasses', ['%doctrine.orm.auto_generate_proxy_classes%']);
419
    }
420
421
    public function testSingleEntityManagerMultipleMappingBundleDefinitions()
422
    {
423
        $container = $this->loadContainer('orm_single_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
424
425
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
426
427
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [
428
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
429
            'Fixtures\Bundles\AnnotationsBundle\Entity',
430
        ]);
431
432
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [
433
            new Reference('doctrine.orm.default_yml_metadata_driver'),
434
            'Fixtures\Bundles\YamlBundle\Entity',
435
        ]);
436
437
        $this->assertDICDefinitionMethodCallAt(2, $definition, 'addDriver', [
438
            new Reference('doctrine.orm.default_xml_metadata_driver'),
439
            'Fixtures\Bundles\XmlBundle',
440
        ]);
441
442
        $annDef = $container->getDefinition('doctrine.orm.default_annotation_metadata_driver');
443
        $this->assertDICConstructorArguments($annDef, [
444
            new Reference('doctrine.orm.metadata.annotation_reader'),
445
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
446
        ]);
447
448
        $ymlDef = $container->getDefinition('doctrine.orm.default_yml_metadata_driver');
449
        $this->assertDICConstructorArguments($ymlDef, [
450
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
451
        ]);
452
453
        $xmlDef = $container->getDefinition('doctrine.orm.default_xml_metadata_driver');
454
        $this->assertDICConstructorArguments($xmlDef, [
455
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
456
        ]);
457
    }
458
459
    public function testMultipleEntityManagersMappingBundleDefinitions()
460
    {
461
        $container = $this->loadContainer('orm_multiple_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
462
463
        $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.');
464
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), 'Set of the existing EntityManagers names is incorrect.');
465
466
        $def1 = $container->getDefinition('doctrine.orm.em1_metadata_driver');
467
        $def2 = $container->getDefinition('doctrine.orm.em2_metadata_driver');
468
469
        $this->assertDICDefinitionMethodCallAt(0, $def1, 'addDriver', [
470
            new Reference('doctrine.orm.em1_annotation_metadata_driver'),
471
            'Fixtures\Bundles\AnnotationsBundle\Entity',
472
        ]);
473
474
        $this->assertDICDefinitionMethodCallAt(0, $def2, 'addDriver', [
475
            new Reference('doctrine.orm.em2_yml_metadata_driver'),
476
            'Fixtures\Bundles\YamlBundle\Entity',
477
        ]);
478
479
        $this->assertDICDefinitionMethodCallAt(1, $def2, 'addDriver', [
480
            new Reference('doctrine.orm.em2_xml_metadata_driver'),
481
            'Fixtures\Bundles\XmlBundle',
482
        ]);
483
484
        $annDef = $container->getDefinition('doctrine.orm.em1_annotation_metadata_driver');
485
        $this->assertDICConstructorArguments($annDef, [
486
            new Reference('doctrine.orm.metadata.annotation_reader'),
487
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
488
        ]);
489
490
        $ymlDef = $container->getDefinition('doctrine.orm.em2_yml_metadata_driver');
491
        $this->assertDICConstructorArguments($ymlDef, [
492
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
493
        ]);
494
495
        $xmlDef = $container->getDefinition('doctrine.orm.em2_xml_metadata_driver');
496
        $this->assertDICConstructorArguments($xmlDef, [
497
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
498
        ]);
499
    }
500
501
    public function testSingleEntityManagerDefaultTableOptions()
502
    {
503
        $container = $this->loadContainer('orm_single_em_default_table_options', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
504
505
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
506
507
        $this->assertArrayHasKey('defaultTableOptions', $param);
508
509
        $defaults = $param['defaultTableOptions'];
510
511
        $this->assertArrayHasKey('charset', $defaults);
512
        $this->assertArrayHasKey('collate', $defaults);
513
        $this->assertArrayHasKey('engine', $defaults);
514
515
        $this->assertEquals('utf8mb4', $defaults['charset']);
516
        $this->assertEquals('utf8mb4_unicode_ci', $defaults['collate']);
517
        $this->assertEquals('InnoDB', $defaults['engine']);
518
    }
519
520
    public function testSetTypes()
521
    {
522
        $container = $this->loadContainer('dbal_types');
523
524
        $this->assertEquals(
525
            ['test' => ['class' => TestType::class, 'commented' => true]],
526
            $container->getParameter('doctrine.dbal.connection_factory.types')
527
        );
528
        $this->assertEquals('%doctrine.dbal.connection_factory.types%', $container->getDefinition('doctrine.dbal.connection_factory')->getArgument(0));
529
    }
530
531
    public function testSetCustomFunctions()
532
    {
533
        $container = $this->loadContainer('orm_functions');
534
535
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
536
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
537
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomNumericFunction', ['test_numeric', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction']);
538
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomDatetimeFunction', ['test_datetime', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction']);
539
    }
540
541 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...
542
    {
543
        $container = $this->loadContainer('orm_namingstrategy');
544
545
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
546
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
547
548
        $this->assertDICDefinitionMethodCallOnce($def1, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.default')]);
549
        $this->assertDICDefinitionMethodCallOnce($def2, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.underscore')]);
550
    }
551
552 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...
553
    {
554
        $container = $this->loadContainer('orm_quotestrategy');
555
556
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
557
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
558
559
        $this->assertDICDefinitionMethodCallOnce($def1, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.default')]);
560
        $this->assertDICDefinitionMethodCallOnce($def2, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.ansi')]);
561
    }
562
563
    public function testSecondLevelCache()
564
    {
565
        $container = $this->loadContainer('orm_second_level_cache');
566
567
        $this->assertTrue($container->has('doctrine.orm.default_configuration'));
568
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.cache_configuration'));
569
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region_cache_driver'));
570
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.regions_configuration'));
571
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.default_cache_factory'));
572
573
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_chain'));
574
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_statistics'));
575
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger1'));
576
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger2'));
577
578
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_entity_region'));
579
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_service_region'));
580
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_query_region_filelock'));
581
582
        $slcFactoryDef       = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
583
        $myEntityRegionDef   = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_entity_region');
584
        $loggerChainDef      = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_chain');
585
        $loggerStatisticsDef = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_statistics');
586
        $myQueryRegionDef    = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_query_region_filelock');
587
        $cacheDriverDef      = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_second_level_cache.region_cache_driver'));
588
        $configDef           = $container->getDefinition('doctrine.orm.default_configuration');
589
        $myEntityRegionArgs  = $myEntityRegionDef->getArguments();
590
        $myQueryRegionArgs   = $myQueryRegionDef->getArguments();
591
        $slcFactoryArgs      = $slcFactoryDef->getArguments();
592
593
        $this->assertDICDefinitionClass($slcFactoryDef, '%doctrine.orm.second_level_cache.default_cache_factory.class%');
594
        $this->assertDICDefinitionClass($myQueryRegionDef, '%doctrine.orm.second_level_cache.filelock_region.class%');
595
        $this->assertDICDefinitionClass($myEntityRegionDef, '%doctrine.orm.second_level_cache.default_region.class%');
596
        $this->assertDICDefinitionClass($loggerChainDef, '%doctrine.orm.second_level_cache.logger_chain.class%');
597
        $this->assertDICDefinitionClass($loggerStatisticsDef, '%doctrine.orm.second_level_cache.logger_statistics.class%');
598
        $this->assertDICDefinitionClass($cacheDriverDef, '%doctrine_cache.array.class%');
599
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setSecondLevelCacheConfiguration');
600
        $this->assertDICDefinitionMethodCallCount($slcFactoryDef, 'setRegion', [], 3);
601
        $this->assertDICDefinitionMethodCallCount($loggerChainDef, 'setLogger', [], 3);
602
603
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[0]);
604
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[1]);
605
606
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myEntityRegionArgs[1]);
607
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myQueryRegionArgs[0]);
608
609
        $this->assertEquals('my_entity_region', $myEntityRegionArgs[0]);
610
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_entity_region_driver', $myEntityRegionArgs[1]);
611
        $this->assertEquals(600, $myEntityRegionArgs[2]);
612
613
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_query_region', $myQueryRegionArgs[0]);
614
        $this->assertContains('/doctrine/orm/slc/filelock', $myQueryRegionArgs[1]);
615
        $this->assertEquals(60, $myQueryRegionArgs[2]);
616
617
        $this->assertEquals('doctrine.orm.default_second_level_cache.regions_configuration', $slcFactoryArgs[0]);
618
        $this->assertEquals('doctrine.orm.default_second_level_cache.region_cache_driver', $slcFactoryArgs[1]);
619
    }
620
621
    public function testSingleEMSetCustomFunctions()
622
    {
623
        $container = $this->loadContainer('orm_single_em_dql_functions');
624
625
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
626
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
627
    }
628
629
    public function testAddCustomHydrationMode()
630
    {
631
        $container = $this->loadContainer('orm_hydration_mode');
632
633
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
634
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomHydrationMode', ['test_hydrator', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator']);
635
    }
636
637
    public function testAddFilter()
638
    {
639
        $container = $this->loadContainer('orm_filters');
640
641
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
642
        $args       = [
643
            ['soft_delete', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
644
            ['myFilter', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
645
        ];
646
        $this->assertDICDefinitionMethodCallCount($definition, 'addFilter', $args, 2);
647
648
        $definition = $container->getDefinition('doctrine.orm.default_manager_configurator');
649
        $this->assertDICConstructorArguments($definition, [['soft_delete', 'myFilter'], ['myFilter' => ['myParameter' => 'myValue', 'mySecondParameter' => 'mySecondValue']]]);
650
651
        // Let's create the instance to check the configurator work.
652
        /** @var EntityManager $entityManager */
653
        $entityManager = $container->get('doctrine.orm.entity_manager');
654
        $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...
655
    }
656
657
    public function testResolveTargetEntity()
658
    {
659
        $container = $this->loadContainer('orm_resolve_target_entity');
660
661
        $definition = $container->getDefinition('doctrine.orm.listeners.resolve_target_entity');
662
        $this->assertDICDefinitionMethodCallOnce($definition, 'addResolveTargetEntity', ['Symfony\Component\Security\Core\User\UserInterface', 'MyUserClass', []]);
663
664
        $this->assertEquals(['doctrine.event_subscriber' => [[]]], $definition->getTags());
665
    }
666
667
    public function testAttachEntityListeners()
668
    {
669
        $container = $this->loadContainer('orm_attach_entity_listener');
670
671
        $definition  = $container->getDefinition('doctrine.orm.default_listeners.attach_entity_listeners');
672
        $methodCalls = $definition->getMethodCalls();
673
674
        $this->assertDICDefinitionMethodCallCount($definition, 'addEntityListener', [], 6);
675
        $this->assertEquals(['doctrine.event_listener' => [ ['event' => 'loadClassMetadata'] ] ], $definition->getTags());
676
677
        $this->assertEquals($methodCalls[0], [
678
            'addEntityListener',
679
            [
680
                'ExternalBundles\Entities\FooEntity',
681
                'MyBundles\Listeners\FooEntityListener',
682
                'prePersist',
683
                null,
684
            ],
685
        ]);
686
687
        $this->assertEquals($methodCalls[1], [
688
            'addEntityListener',
689
            [
690
                'ExternalBundles\Entities\FooEntity',
691
                'MyBundles\Listeners\FooEntityListener',
692
                'postPersist',
693
                'postPersist',
694
            ],
695
        ]);
696
697
        $this->assertEquals($methodCalls[2], [
698
            'addEntityListener',
699
            [
700
                'ExternalBundles\Entities\FooEntity',
701
                'MyBundles\Listeners\FooEntityListener',
702
                'postLoad',
703
                'postLoadHandler',
704
            ],
705
        ]);
706
707
        $this->assertEquals($methodCalls[3], [
708
            'addEntityListener',
709
            [
710
                'ExternalBundles\Entities\BarEntity',
711
                'MyBundles\Listeners\BarEntityListener',
712
                'prePersist',
713
                'prePersist',
714
            ],
715
        ]);
716
717
        $this->assertEquals($methodCalls[4], [
718
            'addEntityListener',
719
            [
720
                'ExternalBundles\Entities\BarEntity',
721
                'MyBundles\Listeners\BarEntityListener',
722
                'prePersist',
723
                'prePersistHandler',
724
            ],
725
        ]);
726
727
        $this->assertEquals($methodCalls[5], [
728
            'addEntityListener',
729
            [
730
                'ExternalBundles\Entities\BarEntity',
731
                'MyBundles\Listeners\LogDeleteEntityListener',
732
                'postDelete',
733
                'postDelete',
734
            ],
735
        ]);
736
    }
737
738
    public function testDbalAutoCommit()
739
    {
740
        $container = $this->loadContainer('dbal_auto_commit');
741
742
        $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration');
743
        $this->assertDICDefinitionMethodCallOnce($definition, 'setAutoCommit', [false]);
744
    }
745
746
    public function testDbalOracleConnectstring()
747
    {
748
        $container = $this->loadContainer('dbal_oracle_connectstring');
749
750
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
751
        $this->assertSame('scott@sales-server:1521/sales.us.example.com', $config['connectstring']);
752
    }
753
754
    public function testDbalOracleInstancename()
755
    {
756
        $container = $this->loadContainer('dbal_oracle_instancename');
757
758
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
759
        $this->assertSame('mySuperInstance', $config['instancename']);
760
    }
761
762
    public function testDbalSchemaFilter()
763
    {
764
        $container = $this->loadContainer('dbal_schema_filter');
765
766
        $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration');
767
        $this->assertDICDefinitionMethodCallOnce($definition, 'setFilterSchemaAssetsExpression', ['^sf2_']);
768
    }
769
770
    public function testEntityListenerResolver()
771
    {
772
        $container = $this->loadContainer('orm_entity_listener_resolver', ['YamlBundle'], new EntityListenerPass());
773
774
        $definition = $container->getDefinition('doctrine.orm.em1_configuration');
775
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em1_entity_listener_resolver')]);
776
777
        $definition = $container->getDefinition('doctrine.orm.em2_configuration');
778
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em2_entity_listener_resolver')]);
779
780
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
781
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener1')]);
782
783
        $listener = $container->getDefinition('entity_listener_resolver');
784
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]);
785
    }
786
787
    public function testAttachEntityListenerTag()
788
    {
789
        $container = $this->getContainer([]);
790
        $loader    = new DoctrineExtension();
791
        $container->registerExtension($loader);
792
        $container->addCompilerPass(new EntityListenerPass());
793
794
        $this->loadFromFile($container, 'orm_attach_entity_listener_tag');
795
796
        $this->compileContainer($container);
797
798
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
799
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener1')]);
800
801
        $listener = $container->getDefinition('doctrine.orm.em2_entity_listener_resolver');
802
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]);
803
804
        $attachListener = $container->getDefinition('doctrine.orm.em1_listeners.attach_entity_listeners');
805
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity1', 'EntityListener1', 'postLoad']);
806
807
        $attachListener = $container->getDefinition('doctrine.orm.em2_listeners.attach_entity_listeners');
808
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity2', 'EntityListener2', 'preFlush', 'preFlushHandler']);
809
    }
810
811
    public function testAttachEntityListenersTwoConnections()
812
    {
813
        $container = $this->getContainer(['YamlBundle']);
814
        $loader    = new DoctrineExtension();
815
        $container->registerExtension($loader);
816
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'));
817
818
        $this->loadFromFile($container, 'orm_attach_entity_listeners_two_connections');
819
820
        $this->compileContainer($container);
821
822
        $defaultEventManager = $container->getDefinition('doctrine.dbal.default_connection.event_manager');
823
        $this->assertDICDefinitionNoMethodCall($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
824
        $this->assertDICDefinitionMethodCallOnce($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
825
826
        $foobarEventManager = $container->getDefinition('doctrine.dbal.foobar_connection.event_manager');
827
        $this->assertDICDefinitionNoMethodCall($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
828
        $this->assertDICDefinitionMethodCallOnce($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
829
    }
830
831
    public function testAttachLazyEntityListener()
832
    {
833
        $container = $this->getContainer([]);
834
        $loader    = new DoctrineExtension();
835
        $container->registerExtension($loader);
836
        $container->addCompilerPass(new EntityListenerPass());
837
838
        $this->loadFromFile($container, 'orm_attach_lazy_entity_listener');
839
840
        $this->compileContainer($container);
841
842
        $resolver1 = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
843
        $this->assertDICDefinitionMethodCallOnce($resolver1, 'registerService', ['EntityListener1', 'entity_listener1']);
844
845
        $resolver2 = $container->findDefinition('custom_entity_listener_resolver');
846
        $this->assertDICDefinitionMethodCallOnce($resolver2, 'registerService', ['EntityListener2', 'entity_listener2']);
847
    }
848
849
    /**
850
     * @expectedException \InvalidArgumentException
851
     * @expectedExceptionMessage EntityListenerServiceResolver
852
     */
853 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...
854
    {
855
        $container = $this->getContainer([]);
856
        $loader    = new DoctrineExtension();
857
        $container->registerExtension($loader);
858
        $container->addCompilerPass(new EntityListenerPass());
859
860
        $this->loadFromFile($container, 'orm_entity_listener_lazy_resolver_without_interface');
861
862
        $this->compileContainer($container);
863
    }
864
865
    public function testPrivateLazyEntityListener()
866
    {
867
        $container = $this->getContainer([]);
868
        $loader    = new DoctrineExtension();
869
        $container->registerExtension($loader);
870
        $container->addCompilerPass(new EntityListenerPass());
871
872
        $this->loadFromFile($container, 'orm_entity_listener_lazy_private');
873
874
        $this->compileContainer($container);
875
876
        $this->assertTrue($container->getDefinition('doctrine.orm.em1_entity_listener_resolver')->isPublic());
877
    }
878
879
    /**
880
     * @expectedException \InvalidArgumentException
881
     * @expectedExceptionMessageRegExp /The service ".*" must not be abstract as this entity listener is lazy-loaded/
882
     */
883 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...
884
    {
885
        $container = $this->getContainer([]);
886
        $loader    = new DoctrineExtension();
887
        $container->registerExtension($loader);
888
        $container->addCompilerPass(new EntityListenerPass());
889
890
        $this->loadFromFile($container, 'orm_entity_listener_lazy_abstract');
891
892
        $this->compileContainer($container);
893
    }
894
895
    public function testRepositoryFactory()
896
    {
897
        $container = $this->loadContainer('orm_repository_factory');
898
899
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
900
        $this->assertDICDefinitionMethodCallOnce($definition, 'setRepositoryFactory', ['repository_factory']);
901
    }
902
903
    private function loadContainer($fixture, array $bundles = ['YamlBundle'], CompilerPassInterface $compilerPass = null)
904
    {
905
        $container = $this->getContainer($bundles);
906
        $container->registerExtension(new DoctrineExtension());
907
908
        $this->loadFromFile($container, $fixture);
909
910
        if ($compilerPass !== null) {
911
            $container->addCompilerPass($compilerPass);
912
        }
913
914
        $this->compileContainer($container);
915
916
        return $container;
917
    }
918
919
    private function getContainer(array $bundles)
920
    {
921
        $map = [];
922
        foreach ($bundles as $bundle) {
923
            require_once __DIR__ . '/Fixtures/Bundles/' . $bundle . '/' . $bundle . '.php';
924
925
            $map[$bundle] = 'Fixtures\\Bundles\\' . $bundle . '\\' . $bundle;
926
        }
927
928
        return new ContainerBuilder(new ParameterBag([
929
            'kernel.name' => 'app',
930
            'kernel.debug' => false,
931
            'kernel.bundles' => $map,
932
            'kernel.cache_dir' => sys_get_temp_dir(),
933
            'kernel.environment' => 'test',
934
            'kernel.root_dir' => __DIR__ . '/../../', // src dir
935
        ]));
936
    }
937
938
    /**
939
     * Assertion on the Class of a DIC Service Definition.
940
     *
941
     * @param string $expectedClass
942
     */
943
    private function assertDICDefinitionClass(Definition $definition, $expectedClass)
944
    {
945
        $this->assertEquals($expectedClass, $definition->getClass(), 'Expected Class of the DIC Container Service Definition is wrong.');
946
    }
947
948
    private function assertDICConstructorArguments(Definition $definition, $args)
949
    {
950
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match.");
951
    }
952
953 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...
954
    {
955
        $calls = $definition->getMethodCalls();
956
        if (! isset($calls[$pos][0])) {
957
            return;
958
        }
959
960
        $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.');
961
962
        if ($params === null) {
963
            return;
964
        }
965
966
        $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
967
    }
968
969
    /**
970
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
971
     *
972
     * @param string $methodName
973
     * @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...
974
     */
975 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...
976
    {
977
        $calls  = $definition->getMethodCalls();
978
        $called = false;
979
        foreach ($calls as $call) {
980
            if ($call[0] !== $methodName) {
981
                continue;
982
            }
983
984
            if ($called) {
985
                $this->fail("Method '" . $methodName . "' is expected to be called only once, a second call was registered though.");
986
            } else {
987
                $called = true;
988
                if ($params !== null) {
989
                    $this->assertEquals($params, $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
990
                }
991
            }
992
        }
993
        if ($called) {
994
            return;
995
        }
996
997
        $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though.");
998
    }
999
1000
    private function assertDICDefinitionMethodCallCount(Definition $definition, $methodName, array $params = [], $nbCalls = 1)
1001
    {
1002
        $calls  = $definition->getMethodCalls();
1003
        $called = 0;
1004
        foreach ($calls as $call) {
1005
            if ($call[0] !== $methodName) {
1006
                continue;
1007
            }
1008
1009
            if ($called > $nbCalls) {
1010
                break;
1011
            }
1012
1013
            if (isset($params[$called])) {
1014
                $this->assertEquals($params[$called], $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1015
            }
1016
            $called++;
1017
        }
1018
1019
        $this->assertEquals($nbCalls, $called, sprintf('The method "%s" should be called %d times', $methodName, $nbCalls));
1020
    }
1021
1022
    /**
1023
     * Assertion for the DI Container, check if the given definition does not contain a method call with the given parameters.
1024
     *
1025
     * @param string $methodName
1026
     * @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...
1027
     */
1028
    private function assertDICDefinitionNoMethodCall(Definition $definition, $methodName, array $params = null)
1029
    {
1030
        $calls = $definition->getMethodCalls();
1031
        foreach ($calls as $call) {
1032
            if ($call[0] !== $methodName) {
1033
                continue;
1034
            }
1035
1036
            if ($params !== null) {
1037
                $this->assertNotEquals($params, $call[1], "Method '" . $methodName . "' is not expected to be called with the given parameters.");
1038
            } else {
1039
                $this->fail("Method '" . $methodName . "' is not expected to be called");
1040
            }
1041
        }
1042
    }
1043
1044
    private function compileContainer(ContainerBuilder $container)
1045
    {
1046
        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
1047
        $container->getCompilerPassConfig()->setRemovingPasses([]);
1048
        $container->compile();
1049
    }
1050
}
1051