Completed
Pull Request — master (#905)
by Gabriel
01:56
created

testLoadMultipleConnections()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 63

Duplication

Lines 12
Ratio 19.05 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 12
loc 63
rs 8.8072
cc 3
nc 4
nop 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection;
4
5
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\EntityListenerPass;
6
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
7
use Doctrine\ORM\EntityManager;
8
use 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);
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);
184
185
        $calls = $container->getDefinition('doctrine.dbal.notset_connection')->getMethodCalls();
186
        $this->assertCount(0, $calls);
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 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
214
            $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
215
        } else {
216
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
217
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
218
        }
219
220
        $this->assertDICConstructorArguments($definition, [
221
            new Reference('doctrine.dbal.default_connection'),
222
            new Reference('doctrine.orm.default_configuration'),
223
        ]);
224
    }
225
226
    /**
227
     * The PDO driver doesn't require a database name to be to set when connecting to a database server
228
     */
229
    public function testLoadSimpleSingleConnectionWithoutDbName()
230
    {
231
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname');
232
233
        /** @var Definition $definition */
234
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
235
236
        $this->assertDICConstructorArguments($definition, [
237
            [
238
                'host' => 'localhost',
239
                'port' => null,
240
                'user' => 'root',
241
                'password' => null,
242
                'driver' => 'pdo_mysql',
243
                'driverOptions' => [],
244
                'defaultTableOptions' => [],
245
            ],
246
            new Reference('doctrine.dbal.default_connection.configuration'),
247
            new Reference('doctrine.dbal.default_connection.event_manager'),
248
            [],
249
        ]);
250
251
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
252
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
253
        if (method_exists($definition, 'getFactory')) {
254
            $factory = $definition->getFactory();
255
        } else {
256
            $factory[0] = $definition->getFactoryClass();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$factory was never initialized. Although not strictly required by PHP, it is generally a good practice to add $factory = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
257
            $factory[1] = $definition->getFactoryMethod();
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
258
        }
259
260
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]);
261
        $this->assertEquals('create', $factory[1]);
262
263
        $this->assertDICConstructorArguments($definition, [
264
            new Reference('doctrine.dbal.default_connection'),
265
            new Reference('doctrine.orm.default_configuration'),
266
        ]);
267
    }
268
269
    public function testLoadSingleConnection()
270
    {
271
        $container = $this->loadContainer('orm_service_single_entity_manager');
272
273
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
274
275
        $this->assertDICConstructorArguments($definition, [
276
            [
277
                'host' => 'localhost',
278
                'driver' => 'pdo_sqlite',
279
                'driverOptions' => [],
280
                'user' => 'sqlite_user',
281
                'port' => null,
282
                'password' => 'sqlite_s3cr3t',
283
                'dbname' => 'sqlite_db',
284
                'memory' => true,
285
                'defaultTableOptions' => [],
286
            ],
287
            new Reference('doctrine.dbal.default_connection.configuration'),
288
            new Reference('doctrine.dbal.default_connection.event_manager'),
289
            [],
290
        ]);
291
292
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
293
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
294 View Code Duplication
        if (method_exists($definition, 'setFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
295
            $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
296
        } else {
297
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
298
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
299
        }
300
301
        $this->assertDICConstructorArguments($definition, [
302
            new Reference('doctrine.dbal.default_connection'),
303
            new Reference('doctrine.orm.default_configuration'),
304
        ]);
305
306
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
307
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', ['Acme\Doctrine\Repository']);
308
    }
309
310
    public function testLoadMultipleConnections()
311
    {
312
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
313
314
        $definition = $container->getDefinition('doctrine.dbal.conn1_connection');
315
316
        $args = $definition->getArguments();
317
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
318
        $this->assertEquals('localhost', $args[0]['host']);
319
        $this->assertEquals('sqlite_user', $args[0]['user']);
320
        $this->assertEquals('doctrine.dbal.conn1_connection.configuration', (string) $args[1]);
321
        $this->assertEquals('doctrine.dbal.conn1_connection.event_manager', (string) $args[2]);
322
323
        $this->assertEquals('doctrine.orm.em2_entity_manager', (string) $container->getAlias('doctrine.orm.entity_manager'));
324
325
        $definition = $container->getDefinition('doctrine.orm.em1_entity_manager');
326
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
327 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
328
            $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
329
        } else {
330
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
331
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
332
        }
333
334
        $arguments = $definition->getArguments();
335
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
336
        $this->assertEquals('doctrine.dbal.conn1_connection', (string) $arguments[0]);
337
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
338
        $this->assertEquals('doctrine.orm.em1_configuration', (string) $arguments[1]);
339
340
        $definition = $container->getDefinition('doctrine.dbal.conn2_connection');
341
342
        $args = $definition->getArguments();
343
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
344
        $this->assertEquals('localhost', $args[0]['host']);
345
        $this->assertEquals('sqlite_user', $args[0]['user']);
346
        $this->assertEquals('doctrine.dbal.conn2_connection.configuration', (string) $args[1]);
347
        $this->assertEquals('doctrine.dbal.conn2_connection.event_manager', (string) $args[2]);
348
349
        $definition = $container->getDefinition('doctrine.orm.em2_entity_manager');
350
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
351 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
352
            $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
353
        } else {
354
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
355
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
356
        }
357
358
        $arguments = $definition->getArguments();
359
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
360
        $this->assertEquals('doctrine.dbal.conn2_connection', (string) $arguments[0]);
361
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
362
        $this->assertEquals('doctrine.orm.em2_configuration', (string) $arguments[1]);
363
364
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
365
        $this->assertEquals('%doctrine_cache.xcache.class%', $definition->getClass());
366
367
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_query_cache'));
368
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
369
370
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_result_cache'));
371
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
372
    }
373
374
    public function testLoadLogging()
375
    {
376
        $container = $this->loadContainer('dbal_logging');
377
378
        $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration');
379
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger')]);
380
381
        $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration');
382
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.profiling.profile')]);
383
384
        $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration');
385
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', [new Reference('doctrine.dbal.logger.chain.both')]);
386
    }
387
388
    public function testEntityManagerMetadataCacheDriverConfiguration()
389
    {
390
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
391
392
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em1_metadata_cache'));
393
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.xcache.class%');
394
395
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.em2_metadata_cache'));
396
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.apc.class%');
397
    }
398
399 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...
400
    {
401
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
402
403
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
404
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.class%');
405
        $this->assertDICDefinitionMethodCallOnce(
406
            $definition,
407
            'setMemcache',
408
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection')]
409
        );
410
411
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection');
412
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.connection.class%');
413
        $this->assertDICDefinitionMethodCallOnce($definition, 'addServer', [
414
            'localhost',
415
            '11211',
416
        ]);
417
    }
418
419 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...
420
    {
421
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_redis');
422
423
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
424
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.class%');
425
        $this->assertDICDefinitionMethodCallOnce(
426
            $definition,
427
            'setRedis',
428
            [new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection')]
429
        );
430
431
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache_redis.connection');
432
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.redis.connection.class%');
433
        $this->assertDICDefinitionMethodCallOnce($definition, 'connect', ['localhost', '6379']);
434
        $this->assertDICDefinitionMethodCallOnce($definition, 'select', [1]);
435
    }
436
437
    public function testDependencyInjectionImportsOverrideDefaults()
438
    {
439
        $container = $this->loadContainer('orm_imports');
440
441
        $cacheDefinition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
442
        $this->assertEquals('%doctrine_cache.apc.class%', $cacheDefinition->getClass());
443
444
        $configDefinition = $container->getDefinition('doctrine.orm.default_configuration');
445
        $this->assertDICDefinitionMethodCallOnce($configDefinition, 'setAutoGenerateProxyClasses', ['%doctrine.orm.auto_generate_proxy_classes%']);
446
    }
447
448
    public function testSingleEntityManagerMultipleMappingBundleDefinitions()
449
    {
450
        $container = $this->loadContainer('orm_single_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
451
452
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
453
454
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [
455
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
456
            'Fixtures\Bundles\AnnotationsBundle\Entity',
457
        ]);
458
459
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [
460
            new Reference('doctrine.orm.default_yml_metadata_driver'),
461
            'Fixtures\Bundles\YamlBundle\Entity',
462
        ]);
463
464
        $this->assertDICDefinitionMethodCallAt(2, $definition, 'addDriver', [
465
            new Reference('doctrine.orm.default_xml_metadata_driver'),
466
            'Fixtures\Bundles\XmlBundle',
467
        ]);
468
469
        $annDef = $container->getDefinition('doctrine.orm.default_annotation_metadata_driver');
470
        $this->assertDICConstructorArguments($annDef, [
471
            new Reference('doctrine.orm.metadata.annotation_reader'),
472
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
473
        ]);
474
475
        $ymlDef = $container->getDefinition('doctrine.orm.default_yml_metadata_driver');
476
        $this->assertDICConstructorArguments($ymlDef, [
477
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
478
        ]);
479
480
        $xmlDef = $container->getDefinition('doctrine.orm.default_xml_metadata_driver');
481
        $this->assertDICConstructorArguments($xmlDef, [
482
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
483
        ]);
484
    }
485
486
    public function testMultipleEntityManagersMappingBundleDefinitions()
487
    {
488
        $container = $this->loadContainer('orm_multiple_em_bundle_mappings', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
489
490
        $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.');
491
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), 'Set of the existing EntityManagers names is incorrect.');
492
493
        $def1 = $container->getDefinition('doctrine.orm.em1_metadata_driver');
494
        $def2 = $container->getDefinition('doctrine.orm.em2_metadata_driver');
495
496
        $this->assertDICDefinitionMethodCallAt(0, $def1, 'addDriver', [
497
            new Reference('doctrine.orm.em1_annotation_metadata_driver'),
498
            'Fixtures\Bundles\AnnotationsBundle\Entity',
499
        ]);
500
501
        $this->assertDICDefinitionMethodCallAt(0, $def2, 'addDriver', [
502
            new Reference('doctrine.orm.em2_yml_metadata_driver'),
503
            'Fixtures\Bundles\YamlBundle\Entity',
504
        ]);
505
506
        $this->assertDICDefinitionMethodCallAt(1, $def2, 'addDriver', [
507
            new Reference('doctrine.orm.em2_xml_metadata_driver'),
508
            'Fixtures\Bundles\XmlBundle',
509
        ]);
510
511
        $annDef = $container->getDefinition('doctrine.orm.em1_annotation_metadata_driver');
512
        $this->assertDICConstructorArguments($annDef, [
513
            new Reference('doctrine.orm.metadata.annotation_reader'),
514
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'AnnotationsBundle' . DIRECTORY_SEPARATOR . 'Entity'],
515
        ]);
516
517
        $ymlDef = $container->getDefinition('doctrine.orm.em2_yml_metadata_driver');
518
        $this->assertDICConstructorArguments($ymlDef, [
519
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'YamlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\YamlBundle\Entity'],
520
        ]);
521
522
        $xmlDef = $container->getDefinition('doctrine.orm.em2_xml_metadata_driver');
523
        $this->assertDICConstructorArguments($xmlDef, [
524
            [__DIR__ . DIRECTORY_SEPARATOR . 'Fixtures' . DIRECTORY_SEPARATOR . 'Bundles' . DIRECTORY_SEPARATOR . 'XmlBundle' . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'doctrine' => 'Fixtures\Bundles\XmlBundle'],
525
        ]);
526
    }
527
528
    public function testSingleEntityManagerDefaultTableOptions()
529
    {
530
        $container = $this->loadContainer('orm_single_em_default_table_options', ['YamlBundle', 'AnnotationsBundle', 'XmlBundle']);
531
532
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
533
534
        $this->assertArrayHasKey('defaultTableOptions', $param);
535
536
        $defaults = $param['defaultTableOptions'];
537
538
        $this->assertArrayHasKey('charset', $defaults);
539
        $this->assertArrayHasKey('collate', $defaults);
540
        $this->assertArrayHasKey('engine', $defaults);
541
542
        $this->assertEquals('utf8mb4', $defaults['charset']);
543
        $this->assertEquals('utf8mb4_unicode_ci', $defaults['collate']);
544
        $this->assertEquals('InnoDB', $defaults['engine']);
545
    }
546
547
    public function testSetTypes()
548
    {
549
        $container = $this->loadContainer('dbal_types');
550
551
        $this->assertEquals(
552
            ['test' => ['class' => TestType::class, 'commented' => true]],
553
            $container->getParameter('doctrine.dbal.connection_factory.types')
554
        );
555
        $this->assertEquals('%doctrine.dbal.connection_factory.types%', $container->getDefinition('doctrine.dbal.connection_factory')->getArgument(0));
556
    }
557
558
    public function testSetCustomFunctions()
559
    {
560
        $container = $this->loadContainer('orm_functions');
561
562
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
563
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
564
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomNumericFunction', ['test_numeric', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestNumericFunction']);
565
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomDatetimeFunction', ['test_datetime', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestDatetimeFunction']);
566
    }
567
568 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...
569
    {
570
        if (version_compare(Version::VERSION, '2.3.0-DEV') < 0) {
571
            $this->markTestSkipped('Naming Strategies are not available');
572
        }
573
        $container = $this->loadContainer('orm_namingstrategy');
574
575
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
576
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
577
578
        $this->assertDICDefinitionMethodCallOnce($def1, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.default')]);
579
        $this->assertDICDefinitionMethodCallOnce($def2, 'setNamingStrategy', [0 => new Reference('doctrine.orm.naming_strategy.underscore')]);
580
    }
581
582 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...
583
    {
584
        if (version_compare(Version::VERSION, '2.3.0-DEV') < 0) {
585
            $this->markTestSkipped('Quote Strategies are not available');
586
        }
587
        $container = $this->loadContainer('orm_quotestrategy');
588
589
        $def1 = $container->getDefinition('doctrine.orm.em1_configuration');
590
        $def2 = $container->getDefinition('doctrine.orm.em2_configuration');
591
592
        $this->assertDICDefinitionMethodCallOnce($def1, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.default')]);
593
        $this->assertDICDefinitionMethodCallOnce($def2, 'setQuoteStrategy', [0 => new Reference('doctrine.orm.quote_strategy.ansi')]);
594
    }
595
596
    public function testSecondLevelCache()
597
    {
598
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
599
            $this->markTestSkipped('Second-level cache requires doctrine-orm 2.5.0 or newer');
600
        }
601
602
        $container = $this->loadContainer('orm_second_level_cache');
603
604
        $this->assertTrue($container->has('doctrine.orm.default_configuration'));
605
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.cache_configuration'));
606
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region_cache_driver'));
607
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.regions_configuration'));
608
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.default_cache_factory'));
609
610
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_chain'));
611
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger_statistics'));
612
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger1'));
613
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.logger.my_service_logger2'));
614
615
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_entity_region'));
616
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_service_region'));
617
        $this->assertTrue($container->has('doctrine.orm.default_second_level_cache.region.my_query_region_filelock'));
618
619
        $slcFactoryDef       = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
620
        $myEntityRegionDef   = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_entity_region');
621
        $loggerChainDef      = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_chain');
622
        $loggerStatisticsDef = $container->getDefinition('doctrine.orm.default_second_level_cache.logger_statistics');
623
        $myQueryRegionDef    = $container->getDefinition('doctrine.orm.default_second_level_cache.region.my_query_region_filelock');
624
        $cacheDriverDef      = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_second_level_cache.region_cache_driver'));
625
        $configDef           = $container->getDefinition('doctrine.orm.default_configuration');
626
        $myEntityRegionArgs  = $myEntityRegionDef->getArguments();
627
        $myQueryRegionArgs   = $myQueryRegionDef->getArguments();
628
        $slcFactoryArgs      = $slcFactoryDef->getArguments();
629
630
        $this->assertDICDefinitionClass($slcFactoryDef, '%doctrine.orm.second_level_cache.default_cache_factory.class%');
631
        $this->assertDICDefinitionClass($myQueryRegionDef, '%doctrine.orm.second_level_cache.filelock_region.class%');
632
        $this->assertDICDefinitionClass($myEntityRegionDef, '%doctrine.orm.second_level_cache.default_region.class%');
633
        $this->assertDICDefinitionClass($loggerChainDef, '%doctrine.orm.second_level_cache.logger_chain.class%');
634
        $this->assertDICDefinitionClass($loggerStatisticsDef, '%doctrine.orm.second_level_cache.logger_statistics.class%');
635
        $this->assertDICDefinitionClass($cacheDriverDef, '%doctrine_cache.array.class%');
636
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setSecondLevelCacheConfiguration');
637
        $this->assertDICDefinitionMethodCallCount($slcFactoryDef, 'setRegion', [], 3);
638
        $this->assertDICDefinitionMethodCallCount($loggerChainDef, 'setLogger', [], 3);
639
640
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[0]);
641
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $slcFactoryArgs[1]);
642
643
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myEntityRegionArgs[1]);
644
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $myQueryRegionArgs[0]);
645
646
        $this->assertEquals('my_entity_region', $myEntityRegionArgs[0]);
647
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_entity_region_driver', $myEntityRegionArgs[1]);
648
        $this->assertEquals(600, $myEntityRegionArgs[2]);
649
650
        $this->assertEquals('doctrine.orm.default_second_level_cache.region.my_query_region', $myQueryRegionArgs[0]);
651
        $this->assertContains('/doctrine/orm/slc/filelock', $myQueryRegionArgs[1]);
652
        $this->assertEquals(60, $myQueryRegionArgs[2]);
653
654
        $this->assertEquals('doctrine.orm.default_second_level_cache.regions_configuration', $slcFactoryArgs[0]);
655
        $this->assertEquals('doctrine.orm.default_second_level_cache.region_cache_driver', $slcFactoryArgs[1]);
656
    }
657
658
    public function testSingleEMSetCustomFunctions()
659
    {
660
        $container = $this->loadContainer('orm_single_em_dql_functions');
661
662
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
663
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomStringFunction', ['test_string', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestStringFunction']);
664
    }
665
666
    public function testAddCustomHydrationMode()
667
    {
668
        $container = $this->loadContainer('orm_hydration_mode');
669
670
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
671
        $this->assertDICDefinitionMethodCallOnce($definition, 'addCustomHydrationMode', ['test_hydrator', 'Symfony\Bundle\DoctrineBundle\Tests\DependencyInjection\TestHydrator']);
672
    }
673
674
    public function testAddFilter()
675
    {
676
        $container = $this->loadContainer('orm_filters');
677
678
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
679
        $args       = [
680
            ['soft_delete', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
681
            ['myFilter', 'Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection\TestFilter'],
682
        ];
683
        $this->assertDICDefinitionMethodCallCount($definition, 'addFilter', $args, 2);
684
685
        $definition = $container->getDefinition('doctrine.orm.default_manager_configurator');
686
        $this->assertDICConstructorArguments($definition, [['soft_delete', 'myFilter'], ['myFilter' => ['myParameter' => 'myValue', 'mySecondParameter' => 'mySecondValue']]]);
687
688
        // Let's create the instance to check the configurator work.
689
        /** @var EntityManager $entityManager */
690
        $entityManager = $container->get('doctrine.orm.entity_manager');
691
        $this->assertCount(2, $entityManager->getFilters()->getEnabledFilters());
692
    }
693
694
    public function testResolveTargetEntity()
695
    {
696
        $container = $this->loadContainer('orm_resolve_target_entity');
697
698
        $definition = $container->getDefinition('doctrine.orm.listeners.resolve_target_entity');
699
        $this->assertDICDefinitionMethodCallOnce($definition, 'addResolveTargetEntity', ['Symfony\Component\Security\Core\User\UserInterface', 'MyUserClass', []]);
700
701
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
702
            $this->assertEquals(['doctrine.event_listener' => [['event' => 'loadClassMetadata']]], $definition->getTags());
703
        } else {
704
            $this->assertEquals(['doctrine.event_subscriber' => [[]]], $definition->getTags());
705
        }
706
    }
707
708
    public function testAttachEntityListeners()
709
    {
710
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
711
            $this->markTestSkipped('This test requires ORM 2.5-dev.');
712
        }
713
714
        $container = $this->loadContainer('orm_attach_entity_listener');
715
716
        $definition  = $container->getDefinition('doctrine.orm.default_listeners.attach_entity_listeners');
717
        $methodCalls = $definition->getMethodCalls();
718
719
        $this->assertDICDefinitionMethodCallCount($definition, 'addEntityListener', [], 6);
720
        $this->assertEquals(['doctrine.event_listener' => [ ['event' => 'loadClassMetadata'] ] ], $definition->getTags());
721
722
        $this->assertEquals($methodCalls[0], [
723
            'addEntityListener',
724
            [
725
                'ExternalBundles\Entities\FooEntity',
726
                'MyBundles\Listeners\FooEntityListener',
727
                'prePersist',
728
                null,
729
            ],
730
        ]);
731
732
        $this->assertEquals($methodCalls[1], [
733
            'addEntityListener',
734
            [
735
                'ExternalBundles\Entities\FooEntity',
736
                'MyBundles\Listeners\FooEntityListener',
737
                'postPersist',
738
                'postPersist',
739
            ],
740
        ]);
741
742
        $this->assertEquals($methodCalls[2], [
743
            'addEntityListener',
744
            [
745
                'ExternalBundles\Entities\FooEntity',
746
                'MyBundles\Listeners\FooEntityListener',
747
                'postLoad',
748
                'postLoadHandler',
749
            ],
750
        ]);
751
752
        $this->assertEquals($methodCalls[3], [
753
            'addEntityListener',
754
            [
755
                'ExternalBundles\Entities\BarEntity',
756
                'MyBundles\Listeners\BarEntityListener',
757
                'prePersist',
758
                'prePersist',
759
            ],
760
        ]);
761
762
        $this->assertEquals($methodCalls[4], [
763
            'addEntityListener',
764
            [
765
                'ExternalBundles\Entities\BarEntity',
766
                'MyBundles\Listeners\BarEntityListener',
767
                'prePersist',
768
                'prePersistHandler',
769
            ],
770
        ]);
771
772
        $this->assertEquals($methodCalls[5], [
773
            'addEntityListener',
774
            [
775
                'ExternalBundles\Entities\BarEntity',
776
                'MyBundles\Listeners\LogDeleteEntityListener',
777
                'postDelete',
778
                'postDelete',
779
            ],
780
        ]);
781
    }
782
783
    public function testDbalAutoCommit()
784
    {
785
        $container = $this->loadContainer('dbal_auto_commit');
786
787
        $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration');
788
        $this->assertDICDefinitionMethodCallOnce($definition, 'setAutoCommit', [false]);
789
    }
790
791
    public function testDbalOracleConnectstring()
792
    {
793
        $container = $this->loadContainer('dbal_oracle_connectstring');
794
795
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
796
        $this->assertSame('scott@sales-server:1521/sales.us.example.com', $config['connectstring']);
797
    }
798
799
    public function testDbalOracleInstancename()
800
    {
801
        $container = $this->loadContainer('dbal_oracle_instancename');
802
803
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
804
        $this->assertSame('mySuperInstance', $config['instancename']);
805
    }
806
807
    public function testDbalSchemaFilter()
808
    {
809
        $container = $this->loadContainer('dbal_schema_filter');
810
811
        $definition = $container->getDefinition('doctrine.dbal.default_connection.configuration');
812
        $this->assertDICDefinitionMethodCallOnce($definition, 'setFilterSchemaAssetsExpression', ['^sf2_']);
813
    }
814
815
    public function testEntityListenerResolver()
816
    {
817
        $container = $this->loadContainer('orm_entity_listener_resolver', ['YamlBundle'], new EntityListenerPass());
818
819
        $definition = $container->getDefinition('doctrine.orm.em1_configuration');
820 View Code Duplication
        if (version_compare(Version::VERSION, '2.4.0-DEV') >= 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
821
            $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em1_entity_listener_resolver')]);
822
        }
823
824
        $definition = $container->getDefinition('doctrine.orm.em2_configuration');
825 View Code Duplication
        if (version_compare(Version::VERSION, '2.4.0-DEV') >= 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
826
            $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityListenerResolver', [new Reference('doctrine.orm.em2_entity_listener_resolver')]);
827
        }
828
829
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
830
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener1')]);
831
832
        $listener = $container->getDefinition('entity_listener_resolver');
833
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]);
834
    }
835
836
    public function testAttachEntityListenerTag()
837
    {
838
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
839
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
840
        }
841
842
        $container = $this->getContainer([]);
843
        $loader    = new DoctrineExtension();
844
        $container->registerExtension($loader);
845
        $container->addCompilerPass(new EntityListenerPass());
846
847
        $this->loadFromFile($container, 'orm_attach_entity_listener_tag');
848
849
        $this->compileContainer($container);
850
851
        $listener = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
852
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener1')]);
853
854
        $listener = $container->getDefinition('doctrine.orm.em2_entity_listener_resolver');
855
        $this->assertDICDefinitionMethodCallOnce($listener, 'register', [new Reference('entity_listener2')]);
856
857
        $attachListener = $container->getDefinition('doctrine.orm.em1_listeners.attach_entity_listeners');
858
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity1', 'EntityListener1', 'postLoad']);
859
860
        $attachListener = $container->getDefinition('doctrine.orm.em2_listeners.attach_entity_listeners');
861
        $this->assertDICDefinitionMethodCallOnce($attachListener, 'addEntityListener', ['My/Entity2', 'EntityListener2', 'preFlush', 'preFlushHandler']);
862
    }
863
864
    public function testAttachEntityListenersTwoConnections()
865
    {
866
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
867
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
868
        }
869
870
        $container = $this->getContainer(['YamlBundle']);
871
        $loader    = new DoctrineExtension();
872
        $container->registerExtension($loader);
873
        $container->addCompilerPass(new RegisterEventListenersAndSubscribersPass('doctrine.connections', 'doctrine.dbal.%s_connection.event_manager', 'doctrine'));
874
875
        $this->loadFromFile($container, 'orm_attach_entity_listeners_two_connections');
876
877
        $this->compileContainer($container);
878
879
        $defaultEventManager = $container->getDefinition('doctrine.dbal.default_connection.event_manager');
880
        $this->assertDICDefinitionNoMethodCall($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
881
        $this->assertDICDefinitionMethodCallOnce($defaultEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
882
883
        $foobarEventManager = $container->getDefinition('doctrine.dbal.foobar_connection.event_manager');
884
        $this->assertDICDefinitionNoMethodCall($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em1_listeners.attach_entity_listeners')]);
885
        $this->assertDICDefinitionMethodCallOnce($foobarEventManager, 'addEventListener', [['loadClassMetadata'], new Reference('doctrine.orm.em2_listeners.attach_entity_listeners')]);
886
    }
887
888
    public function testAttachLazyEntityListener()
889
    {
890
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
891
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
892
        }
893
894
        $container = $this->getContainer([]);
895
        $loader    = new DoctrineExtension();
896
        $container->registerExtension($loader);
897
        $container->addCompilerPass(new EntityListenerPass());
898
899
        $this->loadFromFile($container, 'orm_attach_lazy_entity_listener');
900
901
        $this->compileContainer($container);
902
903
        $resolver1 = $container->getDefinition('doctrine.orm.em1_entity_listener_resolver');
904
        $this->assertDICDefinitionMethodCallOnce($resolver1, 'registerService', ['EntityListener1', 'entity_listener1']);
905
906
        $resolver2 = $container->findDefinition('custom_entity_listener_resolver');
907
        $this->assertDICDefinitionMethodCallOnce($resolver2, 'registerService', ['EntityListener2', 'entity_listener2']);
908
    }
909
910
    /**
911
     * @expectedException \InvalidArgumentException
912
     * @expectedExceptionMessage EntityListenerServiceResolver
913
     */
914 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...
915
    {
916
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
917
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
918
        }
919
920
        $container = $this->getContainer([]);
921
        $loader    = new DoctrineExtension();
922
        $container->registerExtension($loader);
923
        $container->addCompilerPass(new EntityListenerPass());
924
925
        $this->loadFromFile($container, 'orm_entity_listener_lazy_resolver_without_interface');
926
927
        $this->compileContainer($container);
928
    }
929
930
    public function testPrivateLazyEntityListener()
931
    {
932
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
933
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
934
        }
935
936
        $container = $this->getContainer([]);
937
        $loader    = new DoctrineExtension();
938
        $container->registerExtension($loader);
939
        $container->addCompilerPass(new EntityListenerPass());
940
941
        $this->loadFromFile($container, 'orm_entity_listener_lazy_private');
942
943
        $this->compileContainer($container);
944
945
        $this->assertTrue($container->getDefinition('doctrine.orm.em1_entity_listener_resolver')->isPublic());
946
    }
947
948
    /**
949
     * @expectedException \InvalidArgumentException
950
     * @expectedExceptionMessageRegExp /The service ".*" must not be abstract as this entity listener is lazy-loaded/
951
     */
952 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...
953
    {
954
        if (version_compare(Version::VERSION, '2.5.0-DEV') < 0) {
955
            $this->markTestSkipped('Attaching entity listeners by tag requires doctrine-orm 2.5.0 or newer');
956
        }
957
958
        $container = $this->getContainer([]);
959
        $loader    = new DoctrineExtension();
960
        $container->registerExtension($loader);
961
        $container->addCompilerPass(new EntityListenerPass());
962
963
        $this->loadFromFile($container, 'orm_entity_listener_lazy_abstract');
964
965
        $this->compileContainer($container);
966
    }
967
968
    public function testRepositoryFactory()
969
    {
970
        $container = $this->loadContainer('orm_repository_factory');
971
972
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
973
        $this->assertDICDefinitionMethodCallOnce($definition, 'setRepositoryFactory', ['repository_factory']);
974
    }
975
976
    private function loadContainer($fixture, array $bundles = ['YamlBundle'], CompilerPassInterface $compilerPass = null)
977
    {
978
        $container = $this->getContainer($bundles);
979
        $container->registerExtension(new DoctrineExtension());
980
981
        $this->loadFromFile($container, $fixture);
982
983
        if ($compilerPass !== null) {
984
            $container->addCompilerPass($compilerPass);
985
        }
986
987
        $this->compileContainer($container);
988
989
        return $container;
990
    }
991
992
    private function getContainer(array $bundles)
993
    {
994
        $map = [];
995
        foreach ($bundles as $bundle) {
996
            require_once __DIR__ . '/Fixtures/Bundles/' . $bundle . '/' . $bundle . '.php';
997
998
            $map[$bundle] = 'Fixtures\\Bundles\\' . $bundle . '\\' . $bundle;
999
        }
1000
1001
        return new ContainerBuilder(new ParameterBag([
1002
            'kernel.name' => 'app',
1003
            'kernel.debug' => false,
1004
            'kernel.bundles' => $map,
1005
            'kernel.cache_dir' => sys_get_temp_dir(),
1006
            'kernel.environment' => 'test',
1007
            'kernel.root_dir' => __DIR__ . '/../../', // src dir
1008
        ]));
1009
    }
1010
1011
    /**
1012
     * Assertion on the Class of a DIC Service Definition.
1013
     *
1014
     * @param string $expectedClass
1015
     */
1016
    private function assertDICDefinitionClass(Definition $definition, $expectedClass)
1017
    {
1018
        $this->assertEquals($expectedClass, $definition->getClass(), 'Expected Class of the DIC Container Service Definition is wrong.');
1019
    }
1020
1021
    private function assertDICConstructorArguments(Definition $definition, $args)
1022
    {
1023
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match.");
1024
    }
1025
1026 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...
1027
    {
1028
        $calls = $definition->getMethodCalls();
1029
        if (! isset($calls[$pos][0])) {
1030
            return;
1031
        }
1032
1033
        $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.');
1034
1035
        if ($params === null) {
1036
            return;
1037
        }
1038
1039
        $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1040
    }
1041
1042
    /**
1043
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
1044
     *
1045
     * @param string $methodName
1046
     * @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...
1047
     */
1048 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...
1049
    {
1050
        $calls  = $definition->getMethodCalls();
1051
        $called = false;
1052
        foreach ($calls as $call) {
1053
            if ($call[0] !== $methodName) {
1054
                continue;
1055
            }
1056
1057
            if ($called) {
1058
                $this->fail("Method '" . $methodName . "' is expected to be called only once, a second call was registered though.");
1059
            } else {
1060
                $called = true;
1061
                if ($params !== null) {
1062
                    $this->assertEquals($params, $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1063
                }
1064
            }
1065
        }
1066
        if ($called) {
1067
            return;
1068
        }
1069
1070
        $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though.");
1071
    }
1072
1073
    private function assertDICDefinitionMethodCallCount(Definition $definition, $methodName, array $params = [], $nbCalls = 1)
1074
    {
1075
        $calls  = $definition->getMethodCalls();
1076
        $called = 0;
1077
        foreach ($calls as $call) {
1078
            if ($call[0] !== $methodName) {
1079
                continue;
1080
            }
1081
1082
            if ($called > $nbCalls) {
1083
                break;
1084
            }
1085
1086
            if (isset($params[$called])) {
1087
                $this->assertEquals($params[$called], $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
1088
            }
1089
            $called++;
1090
        }
1091
1092
        $this->assertEquals($nbCalls, $called, sprintf('The method "%s" should be called %d times', $methodName, $nbCalls));
1093
    }
1094
1095
    /**
1096
     * Assertion for the DI Container, check if the given definition does not contain a method call with the given parameters.
1097
     *
1098
     * @param string $methodName
1099
     * @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...
1100
     */
1101
    private function assertDICDefinitionNoMethodCall(Definition $definition, $methodName, array $params = null)
1102
    {
1103
        $calls = $definition->getMethodCalls();
1104
        foreach ($calls as $call) {
1105
            if ($call[0] !== $methodName) {
1106
                continue;
1107
            }
1108
1109
            if ($params !== null) {
1110
                $this->assertNotEquals($params, $call[1], "Method '" . $methodName . "' is not expected to be called with the given parameters.");
1111
            } else {
1112
                $this->fail("Method '" . $methodName . "' is not expected to be called");
1113
            }
1114
        }
1115
    }
1116
1117
    private function compileContainer(ContainerBuilder $container)
1118
    {
1119
        $container->getCompilerPassConfig()->setOptimizationPasses([class_exists(ResolveChildDefinitionsPass::class) ? new ResolveChildDefinitionsPass() : new ResolveDefinitionTemplatesPass()]);
0 ignored issues
show
Documentation introduced by
array(class_exists(\Symf...initionTemplatesPass()) is of type array<integer,object<Sym...nitionTemplatesPass>"}>, but the function expects a array<integer,object<Sym...CompilerPassInterface>>.

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...
1120
        $container->getCompilerPassConfig()->setRemovingPasses([]);
1121
        $container->compile();
1122
    }
1123
}
1124