Completed
Pull Request — master (#892)
by Andreas
01:57
created

testDbalSchemaFilter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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