Completed
Pull Request — master (#935)
by
unknown
134:23
created

DummySchemaAssetsFilter   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 18
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 18
rs 10
c 0
b 0
f 0

2 Methods

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