Completed
Push — master ( 441842...a01d99 )
by Mike
02:50
created

AbstractDoctrineExtensionTest   F

Complexity

Total Complexity 81

Size/Duplication

Total Lines 1036
Duplicated Lines 12.74 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 81
lcom 1
cbo 12
dl 132
loc 1036
rs 3.4497
c 0
b 0
f 0

48 Methods

Rating   Name   Duplication   Size   Complexity  
loadFromFile() 0 1 ?
A testDbalLoadFromXmlMultipleConnections() 0 62 1
A testDbalLoadFromXmlSingleConnections() 0 13 1
B testDbalLoadSingleMasterSlaveConnection() 0 25 1
B testDbalLoadPoolShardingConnection() 0 25 1
A testDbalLoadSavepointsForNestedTransactions() 0 15 1
B testLoadSimpleSingleConnection() 6 35 2
B testLoadSimpleSingleConnectionWithoutDbName() 0 39 2
B testLoadSingleConnection() 6 39 2
A testLoadMultipleConnections() 12 63 3
A testLoadLogging() 0 13 1
A testEntityManagerMetadataCacheDriverConfiguration() 0 10 1
A testEntityManagerMemcacheMetadataCacheDriverConfiguration() 0 16 1
A testDependencyInjectionImportsOverrideDefaults() 0 10 1
B testSingleEntityManagerMultipleMappingBundleDefinitions() 0 37 1
B testMultipleEntityManagersMappingBundleDefinitions() 0 41 1
A testSingleEntityManagerDefaultTableOptions() 0 19 1
A testSetTypes() 0 10 1
A testSetCustomFunctions() 0 9 1
A testSetNamingStrategy() 13 13 2
A testSetQuoteStrategy() 13 13 2
A testSecondLevelCache() 0 61 2
A testSingleEMSetCustomFunctions() 0 7 1
A testAddCustomHydrationMode() 0 7 1
A testAddFilter() 0 19 1
A testResolveTargetEntity() 0 13 2
A testAttachEntityListeners() 0 56 2
A testDbalAutoCommit() 0 7 1
A testDbalOracleConnectstring() 0 7 1
A testDbalOracleInstancename() 0 7 1
A testDbalSchemaFilter() 0 7 1
A testEntityListenerResolver() 6 20 3
B testAttachEntityListenerTag() 0 27 2
A testAttachEntityListenersTwoConnections() 0 23 2
A testAttachLazyEntityListener() 0 21 2
A testLazyEntityListenerResolverWithoutCorrectInterface() 15 15 2
A testPrivateLazyEntityListener() 15 15 2
A testAbstractLazyEntityListener() 15 15 2
A testRepositoryFactory() 0 7 1
A loadContainer() 0 15 2
A getContainer() 0 17 2
A assertDICDefinitionClass() 0 4 1
A assertDICConstructorArguments() 0 4 1
A assertDICDefinitionMethodCallAt() 11 11 3
B assertDICDefinitionMethodCallOnce() 20 20 6
B assertDICDefinitionMethodCallCount() 0 19 5
A assertDICDefinitionNoMethodCall() 0 13 4
A compileContainer() 0 6 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AbstractDoctrineExtensionTest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractDoctrineExtensionTest, and based on these observations, apply Extract Interface, too.

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