Completed
Pull Request — master (#443)
by Peter
05:01
created

testDependencyInjectionImportsOverrideDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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