Completed
Pull Request — master (#690)
by Dmitriy
02:13
created

testDefaultConnectionWithTypes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
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 PHPUnit\Framework\TestCase;
21
use Symfony\Bridge\Doctrine\DependencyInjection\CompilerPass\RegisterEventListenersAndSubscribersPass;
22
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
23
use Symfony\Component\DependencyInjection\ContainerBuilder;
24
use Symfony\Component\DependencyInjection\Definition;
25
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
26
use Symfony\Component\DependencyInjection\Reference;
27
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
28
29
abstract class AbstractDoctrineExtensionTest extends TestCase
30
{
31
    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...
32
33
    public function testDbalLoadFromXmlMultipleConnections()
34
    {
35
        $container = $this->loadContainer('dbal_service_multiple_connections');
36
37
        // doctrine.dbal.mysql_connection
38
        $config = $container->getDefinition('doctrine.dbal.mysql_connection')->getArgument(0);
39
40
        $this->assertEquals('mysql_s3cr3t', $config['password']);
41
        $this->assertEquals('mysql_user', $config['user']);
42
        $this->assertEquals('mysql_db', $config['dbname']);
43
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
44
45
        // doctrine.dbal.sqlite_connection
46
        $config = $container->getDefinition('doctrine.dbal.sqlite_connection')->getArgument(0);
47
        $this->assertSame('pdo_sqlite', $config['driver']);
48
        $this->assertSame('sqlite_db', $config['dbname']);
49
        $this->assertSame('sqlite_user', $config['user']);
50
        $this->assertSame('sqlite_s3cr3t', $config['password']);
51
        $this->assertSame('/tmp/db.sqlite', $config['path']);
52
        $this->assertTrue($config['memory']);
53
54
        // doctrine.dbal.oci8_connection
55
        $config = $container->getDefinition('doctrine.dbal.oci_connection')->getArgument(0);
56
        $this->assertSame('oci8', $config['driver']);
57
        $this->assertSame('oracle_db', $config['dbname']);
58
        $this->assertSame('oracle_user', $config['user']);
59
        $this->assertSame('oracle_s3cr3t', $config['password']);
60
        $this->assertSame('oracle_service', $config['servicename']);
61
        $this->assertTrue($config['service']);
62
        $this->assertTrue($config['pooled']);
63
        $this->assertSame('utf8', $config['charset']);
64
65
        // doctrine.dbal.ibmdb2_connection
66
        $config = $container->getDefinition('doctrine.dbal.ibmdb2_connection')->getArgument(0);
67
        $this->assertSame('ibm_db2', $config['driver']);
68
        $this->assertSame('ibmdb2_db', $config['dbname']);
69
        $this->assertSame('ibmdb2_user', $config['user']);
70
        $this->assertSame('ibmdb2_s3cr3t', $config['password']);
71
        $this->assertSame('TCPIP', $config['protocol']);
72
73
        // doctrine.dbal.pgsql_connection
74
        $config = $container->getDefinition('doctrine.dbal.pgsql_connection')->getArgument(0);
75
        $this->assertSame('pdo_pgsql', $config['driver']);
76
        $this->assertSame('pgsql_db', $config['dbname']);
77
        $this->assertSame('pgsql_user', $config['user']);
78
        $this->assertSame('pgsql_s3cr3t', $config['password']);
79
        $this->assertSame('require', $config['sslmode']);
80
        $this->assertSame('postgresql-ca.pem', $config['sslrootcert']);
81
        $this->assertSame('utf8', $config['charset']);
82
83
        // doctrine.dbal.sqlanywhere_connection
84
        $config = $container->getDefinition('doctrine.dbal.sqlanywhere_connection')->getArgument(0);
85
        $this->assertSame('sqlanywhere', $config['driver']);
86
        $this->assertSame('localhost', $config['host']);
87
        $this->assertSame(2683, $config['port']);
88
        $this->assertSame('sqlanywhere_server', $config['server']);
89
        $this->assertSame('sqlanywhere_db', $config['dbname']);
90
        $this->assertSame('sqlanywhere_user', $config['user']);
91
        $this->assertSame('sqlanywhere_s3cr3t', $config['password']);
92
        $this->assertTrue($config['persistent']);
93
        $this->assertSame('utf8', $config['charset']);
94
    }
95
96
    public function testDbalLoadFromXmlSingleConnections()
97
    {
98
        $container = $this->loadContainer('dbal_service_single_connection');
99
100
        // doctrine.dbal.mysql_connection
101
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
102
103
        $this->assertEquals('mysql_s3cr3t', $config['password']);
104
        $this->assertEquals('mysql_user', $config['user']);
105
        $this->assertEquals('mysql_db', $config['dbname']);
106
        $this->assertEquals('/path/to/mysqld.sock', $config['unix_socket']);
107
        $this->assertEquals('5.6.20', $config['serverVersion']);
108
    }
109
110
    public function testDbalLoadSingleMasterSlaveConnection()
111
    {
112
        $container = $this->loadContainer('dbal_service_single_master_slave_connection');
113
114
        // doctrine.dbal.mysql_connection
115
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
116
117
        $this->assertEquals('Doctrine\\DBAL\\Connections\\MasterSlaveConnection', $param['wrapperClass']);
118
        $this->assertTrue($param['keepSlave']);
119
        $this->assertEquals(
120
            array('user' => 'mysql_user', 'password' => 'mysql_s3cr3t',
121
                  'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost',
122
                  'unix_socket' => '/path/to/mysqld.sock',
123
                  'defaultTableOptions' => array(),
124
            ),
125
            $param['master']
126
        );
127
        $this->assertEquals(
128
            array(
129
                'user' => 'slave_user', 'password' => 'slave_s3cr3t', 'port' => null, 'dbname' => 'slave_db',
130
                'host' => 'localhost', 'unix_socket' => '/path/to/mysqld_slave.sock',
131
            ),
132
            $param['slaves']['slave1']
133
        );
134
    }
135
136
    public function testDbalLoadPoolShardingConnection()
137
    {
138
        $container = $this->loadContainer('dbal_service_pool_sharding_connection');
139
140
        // doctrine.dbal.mysql_connection
141
        $param = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
142
143
        $this->assertEquals('Doctrine\\DBAL\\Sharding\\PoolingShardConnection', $param['wrapperClass']);
144
        $this->assertEquals(new Reference('foo.shard_choser'), $param['shardChoser']);
145
        $this->assertEquals(
146
            array('user' => 'mysql_user', 'password' => 'mysql_s3cr3t',
147
                  'port' => null, 'dbname' => 'mysql_db', 'host' => 'localhost',
148
                  'unix_socket' => '/path/to/mysqld.sock',
149
                  'defaultTableOptions' => array(),
150
            ),
151
            $param['global']
152
        );
153
        $this->assertEquals(
154
            array(
155
                'user' => 'shard_user', 'password' => 'shard_s3cr3t', 'port' => null, 'dbname' => 'shard_db',
156
                'host' => 'localhost', 'unix_socket' => '/path/to/mysqld_shard.sock', 'id' => 1,
157
            ),
158
            $param['shards'][0]
159
        );
160
    }
161
162
    public function testDbalLoadSavepointsForNestedTransactions()
163
    {
164
        $container = $this->loadContainer('dbal_savepoints');
165
166
        $calls = $container->getDefinition('doctrine.dbal.savepoints_connection')->getMethodCalls();
167
        $this->assertCount(1, $calls);
168
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
169
        $this->assertTrue($calls[0][1][0]);
170
171
        $calls = $container->getDefinition('doctrine.dbal.nosavepoints_connection')->getMethodCalls();
172
        $this->assertCount(0, $calls);
173
174
        $calls = $container->getDefinition('doctrine.dbal.notset_connection')->getMethodCalls();
175
        $this->assertCount(0, $calls);
176
    }
177
178
    public function testLoadSimpleSingleConnection()
179
    {
180
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
181
182
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
183
184
        $this->assertDICConstructorArguments($definition, array(
185
            array(
186
                'dbname' => 'db',
187
                'host' => 'localhost',
188
                'port' => null,
189
                'user' => 'root',
190
                'password' => null,
191
                'driver' => 'pdo_mysql',
192
                'driverOptions' => array(),
193
                'defaultTableOptions' => array(),
194
            ),
195
            new Reference('doctrine.dbal.default_connection.configuration'),
196
            new Reference('doctrine.dbal.default_connection.event_manager'),
197
            array(),
198
        ));
199
200
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
201
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
202 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...
203
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
204
        } else {
205
            $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...
206
            $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...
207
        }
208
209
        $this->assertDICConstructorArguments($definition, array(
210
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
211
        ));
212
    }
213
214
    /**
215
     * The PDO driver doesn't require a database name to be to set when connecting to a database server
216
     */
217
    public function testLoadSimpleSingleConnectionWithoutDbName()
218
    {
219
220
        $container = $this->loadContainer('orm_service_simple_single_entity_manager_without_dbname');
221
222
        /** @var Definition $definition */
223
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
224
225
        $this->assertDICConstructorArguments($definition, array(
226
                array(
227
                    'host' => 'localhost',
228
                    'port' => null,
229
                    'user' => 'root',
230
                    'password' => null,
231
                    'driver' => 'pdo_mysql',
232
                    'driverOptions' => array(),
233
                    'defaultTableOptions' => array(),
234
                ),
235
                new Reference('doctrine.dbal.default_connection.configuration'),
236
                new Reference('doctrine.dbal.default_connection.event_manager'),
237
                array(),
238
            ));
239
240
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
241
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
242
        if (method_exists($definition, 'getFactory')) {
243
            $factory = $definition->getFactory();
244
        } else {
245
            $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...
246
            $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...
247
        }
248
249
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $factory[0]);
250
        $this->assertEquals('create', $factory[1]);
251
252
        $this->assertDICConstructorArguments($definition, array(
253
                new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration')
254
            ));
255
    }
256
257
    public function testLoadSingleConnection()
258
    {
259
        $container = $this->loadContainer('orm_service_single_entity_manager');
260
261
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
262
263
        $this->assertDICConstructorArguments($definition, array(
264
            array(
265
                'host' => 'localhost',
266
                'driver' => 'pdo_sqlite',
267
                'driverOptions' => array(),
268
                'user' => 'sqlite_user',
269
                'port' => null,
270
                'password' => 'sqlite_s3cr3t',
271
                'dbname' => 'sqlite_db',
272
                'memory' => true,
273
                'defaultTableOptions' => array(),
274
            ),
275
            new Reference('doctrine.dbal.default_connection.configuration'),
276
            new Reference('doctrine.dbal.default_connection.event_manager'),
277
            array(),
278
        ));
279
280
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
281
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
282 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...
283
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
284
        } else {
285
            $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...
286
            $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...
287
        }
288
289
        $this->assertDICConstructorArguments($definition, array(
290
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
291
        ));
292
293
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
294
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setDefaultRepositoryClassName', array('Acme\Doctrine\Repository'));
295
    }
296
297
    public function testLoadMultipleConnections()
298
    {
299
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
300
301
        $definition = $container->getDefinition('doctrine.dbal.conn1_connection');
302
303
        $args = $definition->getArguments();
304
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
305
        $this->assertEquals('localhost', $args[0]['host']);
306
        $this->assertEquals('sqlite_user', $args[0]['user']);
307
        $this->assertEquals('doctrine.dbal.conn1_connection.configuration', (string) $args[1]);
308
        $this->assertEquals('doctrine.dbal.conn1_connection.event_manager', (string) $args[2]);
309
310
        $this->assertEquals('doctrine.orm.em2_entity_manager', (string) $container->getAlias('doctrine.orm.entity_manager'));
311
312
        $definition = $container->getDefinition('doctrine.orm.em1_entity_manager');
313
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
314 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...
315
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
316
        } else {
317
            $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...
318
            $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...
319
        }
320
321
        $arguments = $definition->getArguments();
322
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
323
        $this->assertEquals('doctrine.dbal.conn1_connection', (string) $arguments[0]);
324
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
325
        $this->assertEquals('doctrine.orm.em1_configuration', (string) $arguments[1]);
326
327
        $definition = $container->getDefinition('doctrine.dbal.conn2_connection');
328
329
        $args = $definition->getArguments();
330
        $this->assertEquals('pdo_sqlite', $args[0]['driver']);
331
        $this->assertEquals('localhost', $args[0]['host']);
332
        $this->assertEquals('sqlite_user', $args[0]['user']);
333
        $this->assertEquals('doctrine.dbal.conn2_connection.configuration', (string) $args[1]);
334
        $this->assertEquals('doctrine.dbal.conn2_connection.event_manager', (string) $args[2]);
335
336
        $definition = $container->getDefinition('doctrine.orm.em2_entity_manager');
337
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
338 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...
339
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
340
        } else {
341
            $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...
342
            $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...
343
        }
344
345
        $arguments = $definition->getArguments();
346
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
347
        $this->assertEquals('doctrine.dbal.conn2_connection', (string) $arguments[0]);
348
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
349
        $this->assertEquals('doctrine.orm.em2_configuration', (string) $arguments[1]);
350
351
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_metadata_cache'));
352
        $this->assertEquals('%doctrine_cache.xcache.class%', $definition->getClass());
353
354
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_query_cache'));
355
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
356
357
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_result_cache'));
358
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
359
    }
360
361
    public function testLoadLogging()
362
    {
363
        $container = $this->loadContainer('dbal_logging');
364
365
        $definition = $container->getDefinition('doctrine.dbal.log_connection.configuration');
366
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger')));
367
368
        $definition = $container->getDefinition('doctrine.dbal.profile_connection.configuration');
369
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger.profiling.profile')));
370
371
        $definition = $container->getDefinition('doctrine.dbal.both_connection.configuration');
372
        $this->assertDICDefinitionMethodCallOnce($definition, 'setSQLLogger', array(new Reference('doctrine.dbal.logger.chain.both')));
373
    }
374
375
    public function testEntityManagerMetadataCacheDriverConfiguration()
376
    {
377
        $container = $this->loadContainer('orm_service_multiple_entity_managers');
378
379
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.em1_metadata_cache'));
380
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.xcache.class%');
381
382
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.em2_metadata_cache'));
383
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.apc.class%');
384
    }
385
386 View Code Duplication
    public function testEntityManagerMemcacheMetadataCacheDriverConfiguration()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
387
    {
388
        $container = $this->loadContainer('orm_service_simple_single_entity_manager');
389
390
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache'));
391
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.class%');
392
        $this->assertDICDefinitionMethodCallOnce($definition, 'setMemcache',
393
            array(new Reference('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection'))
394
        );
395
396
        $definition = $container->getDefinition('doctrine_cache.services.doctrine.orm.default_metadata_cache.connection');
397
        $this->assertDICDefinitionClass($definition, '%doctrine_cache.memcache.connection.class%');
398
        $this->assertDICDefinitionMethodCallOnce($definition, 'addServer', array(
399
            'localhost', '11211',
400
        ));
401
    }
402
403 View Code Duplication
    public function testEntityManagerRedisMetadataCacheDriverConfigurationWithDatabaseKey()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

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