Completed
Push — master ( eb6e4f...312ed0 )
by
unknown
12s
created

DoctrineExtensionTest::getContainer()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2
c 0
b 0
f 0
cc 4
eloc 13
nc 5
nop 2
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\DoctrineExtension;
18
use Doctrine\Bundle\DoctrineBundle\Tests\Builder\BundleConfigurationBuilder;
19
use Doctrine\Common\Persistence\ManagerRegistry;
20
use Doctrine\Common\Persistence\ObjectManager;
21
use Doctrine\Common\Proxy\AbstractProxyFactory;
22
use Doctrine\DBAL\Connection;
23
use Doctrine\DBAL\Driver\Connection as DriverConnection;
24
use Doctrine\ORM\EntityManagerInterface;
25
use Doctrine\ORM\Version;
26
use PHPUnit\Framework\TestCase;
27
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
28
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
29
use Symfony\Component\DependencyInjection\ContainerBuilder;
30
use Symfony\Component\DependencyInjection\Definition;
31
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
32
use Symfony\Component\DependencyInjection\Reference;
33
34
class DoctrineExtensionTest extends TestCase
35
{
36
    public function testAutowiringAlias()
37
    {
38
        $container = $this->getContainer();
39
        $extension = new DoctrineExtension();
40
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
41
42
        $extension->load(array($config), $container);
43
44
        $expectedAliases = array(
45
            DriverConnection::class => 'database_connection',
46
            Connection::class => 'database_connection',
47
            EntityManagerInterface::class => 'doctrine.orm.entity_manager',
48
        );
49
50
        foreach ($expectedAliases as $id => $target) {
51
            $this->assertTrue($container->hasAlias($id), sprintf('The container should have a `%s` alias for autowiring support.', $id));
52
53
            $alias = $container->getAlias($id);
54
            $this->assertEquals($target, (string) $alias, sprintf('The autowiring for `%s` should use `%s`.', $id, $target));
55
            $this->assertFalse($alias->isPublic(), sprintf('The autowiring alias for `%s` should be private.', $id, $target));
56
        }
57
    }
58
59
    public function testPublicServicesAndAliases()
60
    {
61
        $container = $this->getContainer();
62
        $extension = new DoctrineExtension();
63
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
64
65
        $extension->load(array($config), $container);
66
67
        $this->assertTrue($container->getDefinition('doctrine')->isPublic());
68
        $this->assertTrue($container->getAlias('doctrine.orm.entity_manager')->isPublic());
69
        $this->assertTrue($container->getAlias('database_connection')->isPublic());
70
    }
71
72
    public function testDbalGenerateDefaultConnectionConfiguration()
73
    {
74
        $container = $this->getContainer();
75
        $extension = new DoctrineExtension();
76
77
        $container->registerExtension($extension);
78
79
        $extension->load(array(array('dbal' => array())), $container);
80
81
        // doctrine.dbal.default_connection
82
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3));
83
        $this->assertEquals('default', $container->getParameter('doctrine.default_connection'));
84
        $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']);
85
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']);
86
        $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']);
87
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']);
88
        $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']);
89
        $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']);
90
    }
91
92
    public function testDbalOverrideDefaultConnection()
93
    {
94
        $container = $this->getContainer();
95
        $extension = new DoctrineExtension();
96
97
        $container->registerExtension($extension);
98
99
        $extension->load(array(array(), array('dbal' => array('default_connection' => 'foo')), array()), $container);
100
101
        // doctrine.dbal.default_connection
102
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options');
103
        $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options');
104
    }
105
106
    /**
107
     * @expectedException \LogicException
108
     * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well.
109
     */
110
    public function testOrmRequiresDbal()
111
    {
112
        $extension = new DoctrineExtension();
113
114
        $extension->load(array(array('orm' => array('auto_mapping' => true))), $this->getContainer());
115
    }
116
117
    public function getAutomappingConfigurations()
118
    {
119
        return array(
120
            array(
121
                array(
122
                    'em1' => array(
123
                        'mappings' => array(
124
                            'YamlBundle' => null,
125
                        ),
126
                    ),
127
                    'em2' => array(
128
                        'mappings' => array(
129
                            'XmlBundle' => null,
130
                        ),
131
                    ),
132
                ),
133
            ),
134
            array(
135
                array(
136
                    'em1' => array(
137
                        'auto_mapping' => true,
138
                    ),
139
                    'em2' => array(
140
                        'mappings' => array(
141
                            'XmlBundle' => null,
142
                        ),
143
                    ),
144
                ),
145
            ),
146
            array(
147
                array(
148
                    'em1' => array(
149
                        'auto_mapping' => true,
150
                        'mappings' => array(
151
                            'YamlBundle' => null,
152
                        ),
153
                    ),
154
                    'em2' => array(
155
                        'mappings' => array(
156
                            'XmlBundle' => null,
157
                        ),
158
                    ),
159
                ),
160
            ),
161
        );
162
    }
163
164
    /**
165
     * @dataProvider getAutomappingConfigurations
166
     */
167
    public function testAutomapping(array $entityManagers)
168
    {
169
        $extension = new DoctrineExtension();
170
171
        if (!method_exists($extension, 'fixManagersAutoMappings')) {
172
            $this->markTestSkipped('Auto mapping with multiple managers available with Symfony ~2.6');
173
        }
174
175
        $container = $this->getContainer(array(
0 ignored issues
show
Documentation introduced by
array('YamlBundle', 'XmlBundle') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
176
            'YamlBundle',
177
            'XmlBundle',
178
        ));
179
180
        $extension->load(
181
            array(
182
                array(
183
                    'dbal' => array(
184
                        'default_connection' => 'cn1',
185
                        'connections' => array(
186
                            'cn1' => array(),
187
                            'cn2' => array(),
188
                        ),
189
                    ),
190
                    'orm' => array(
191
                        'entity_managers' => $entityManagers,
192
                    ),
193
                ),
194
            ), $container);
195
196
        $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration');
197
        $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration');
198
199
        $this->assertContains(
200
            array(
201
                'setEntityNamespaces',
202
                array(
203
                    array(
204
                        'YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity',
205
                    ),
206
                ),
207
            ),
208
            $configEm1->getMethodCalls()
209
        );
210
211
        $this->assertContains(
212
            array(
213
                'setEntityNamespaces',
214
                array(
215
                    array(
216
                        'XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity',
217
                    ),
218
                ),
219
            ),
220
            $configEm2->getMethodCalls()
221
        );
222
    }
223
224
    public function testDbalLoad()
225
    {
226
        $container = $this->getContainer();
227
        $extension = new DoctrineExtension();
228
229
        $extension->load(array(
230
            array('dbal' => array('connections' => array('default' => array('password' => 'foo')))),
231
            array(),
232
            array('dbal' => array('default_connection' => 'foo')),
233
            array()), $container);
234
235
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
236
237
        $this->assertEquals('foo', $config['password']);
238
        $this->assertEquals('root', $config['user']);
239
    }
240
241
    public function testDbalWrapperClass()
242
    {
243
        $container = $this->getContainer();
244
        $extension = new DoctrineExtension();
245
246
        $extension->load(
247
            array(
248
                array('dbal' => array('connections' => array(
249
                    'default' => array('password' => 'foo', 'wrapper_class' => TestWrapperClass::class),
250
                    'second' => array('password' => 'boo'),
251
                ))),
252
                array(),
253
                array('dbal' => array('default_connection' => 'foo')),
254
                array()
255
            ),
256
            $container
257
        );
258
259
        $this->assertEquals(TestWrapperClass::class, $container->getDefinition('doctrine.dbal.default_connection')->getClass());
260
        $this->assertNull($container->getDefinition('doctrine.dbal.second_connection')->getClass());
261
    }
262
263
    public function testDependencyInjectionConfigurationDefaults()
264
    {
265
        $container = $this->getContainer();
266
        $extension = new DoctrineExtension();
267
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
268
269
        $extension->load(array($config), $container);
270
271
        $this->assertFalse($container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
272
        $this->assertEquals('Doctrine\ORM\Configuration', $container->getParameter('doctrine.orm.configuration.class'));
273
        $this->assertEquals('Doctrine\ORM\EntityManager', $container->getParameter('doctrine.orm.entity_manager.class'));
274
        $this->assertEquals('Proxies', $container->getParameter('doctrine.orm.proxy_namespace'));
275
        $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.orm.cache.array.class'));
276
        $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.orm.cache.apc.class'));
277
        $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.orm.cache.memcache.class'));
278
        $this->assertEquals('localhost', $container->getParameter('doctrine.orm.cache.memcache_host'));
279
        $this->assertEquals('11211', $container->getParameter('doctrine.orm.cache.memcache_port'));
280
        $this->assertEquals('Memcache', $container->getParameter('doctrine.orm.cache.memcache_instance.class'));
281
        $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.orm.cache.xcache.class'));
282
        $this->assertEquals('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->getParameter('doctrine.orm.metadata.driver_chain.class'));
283
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.orm.metadata.annotation.class'));
284
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver', $container->getParameter('doctrine.orm.metadata.xml.class'));
285
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver', $container->getParameter('doctrine.orm.metadata.yml.class'));
286
287
        // second-level cache
288
        $this->assertEquals('Doctrine\ORM\Cache\DefaultCacheFactory', $container->getParameter('doctrine.orm.second_level_cache.default_cache_factory.class'));
289
        $this->assertEquals('Doctrine\ORM\Cache\Region\DefaultRegion', $container->getParameter('doctrine.orm.second_level_cache.default_region.class'));
290
        $this->assertEquals('Doctrine\ORM\Cache\Region\FileLockRegion', $container->getParameter('doctrine.orm.second_level_cache.filelock_region.class'));
291
        $this->assertEquals('Doctrine\ORM\Cache\Logging\CacheLoggerChain', $container->getParameter('doctrine.orm.second_level_cache.logger_chain.class'));
292
        $this->assertEquals('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger', $container->getParameter('doctrine.orm.second_level_cache.logger_statistics.class'));
293
        $this->assertEquals('Doctrine\ORM\Cache\CacheConfiguration', $container->getParameter('doctrine.orm.second_level_cache.cache_configuration.class'));
294
        $this->assertEquals('Doctrine\ORM\Cache\RegionsConfiguration', $container->getParameter('doctrine.orm.second_level_cache.regions_configuration.class'));
295
296
297
        $config = BundleConfigurationBuilder::createBuilder()
298
            ->addBaseConnection()
299
            ->addEntityManager(array(
300
                'proxy_namespace' => 'MyProxies',
301
                'auto_generate_proxy_classes' => true,
302
                'default_entity_manager' => 'default',
303
                'entity_managers' => array(
304
                    'default' => array(
305
                        'mappings' => array('YamlBundle' => array()),
306
                    ),
307
                ),
308
            ))
309
            ->build();
310
311
        $container = $this->getContainer();
312
        $extension->load(array($config), $container);
313
        $this->compileContainer($container);
314
315
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
316
317
        $args = $definition->getArguments();
318
        $this->assertEquals('pdo_mysql', $args[0]['driver']);
319
        $this->assertEquals('localhost', $args[0]['host']);
320
        $this->assertEquals('root', $args[0]['user']);
321
        $this->assertEquals('doctrine.dbal.default_connection.configuration', (string) $args[1]);
322
        $this->assertEquals('doctrine.dbal.default_connection.event_manager', (string) $args[2]);
323
        $this->assertCount(0, $definition->getMethodCalls());
324
325
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
326
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
327 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
328
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
329
        } else {
330
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

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

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

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

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

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

Loading history...
332
        }
333
334
        $this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $container->getParameter('doctrine.entity_managers'), "Set of the existing EntityManagers names is incorrect.");
335
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), "Set of the existing EntityManagers names is incorrect.");
336
337
        $arguments = $definition->getArguments();
338
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
339
        $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]);
340
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
341
        $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]);
342
343
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
344
        $calls = array_values($definition->getMethodCalls());
345
        $this->assertEquals(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'), $calls[0][1][0]);
346
        $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]);
347
        $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]);
348
        $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]);
349
350
        if (version_compare(Version::VERSION, "2.3.0-DEV") >= 0) {
351
            $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]);
352
            $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]);
353
        }
354
        if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) {
355
            $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]);
356
        }
357
358
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
359
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
360
361
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_query_cache'));
362
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
363
364
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_result_cache'));
365
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
366
    }
367
368
    public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection()
369
    {
370
        $container = $this->getContainer();
371
        $extension = new DoctrineExtension();
372
373
        $extension->load(array(array('dbal' => array('connections' => array(
374
            'default' => array('password' => 'foo', 'use_savepoints' => true)
375
        )))), $container);
376
377
        $calls = $container->getDefinition('doctrine.dbal.default_connection')->getMethodCalls();
378
        $this->assertCount(1, $calls);
379
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
380
        $this->assertTrue($calls[0][1][0]);
381
    }
382
383
    public function testAutoGenerateProxyClasses()
384
    {
385
        $container = $this->getContainer();
386
        $extension = new DoctrineExtension();
387
388
        $config = BundleConfigurationBuilder::createBuilder()
389
            ->addBaseConnection()
390
            ->addEntityManager(array(
391
                'proxy_namespace' => 'MyProxies',
392
                'auto_generate_proxy_classes' => 'eval',
393
                'default_entity_manager' => 'default',
394
                'entity_managers' => array(
395
                    'default' => array(
396
                        'mappings' => array('YamlBundle' => array()),
397
                    ),
398
                ),
399
            ))
400
            ->build();
401
402
        $extension->load(array($config), $container);
403
404
        $this->assertEquals(AbstractProxyFactory::AUTOGENERATE_EVAL, $container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
405
    }
406
407
    public function testSingleEntityManagerWithDefaultConfiguration()
408
    {
409
        $container = $this->getContainer();
410
        $extension = new DoctrineExtension();
411
412
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
413
414
        $extension->load(array($configurationArray), $container);
415
        $this->compileContainer($container);
416
417
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
418
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
419 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...
420
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
421
        } else {
422
            $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...
423
            $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...
424
        }
425
426
        $this->assertDICConstructorArguments($definition, array(
427
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
428
        ));
429
    }
430
431
    public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration()
432
    {
433
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
434
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
435
        }
436
        $container = $this->getContainer();
437
        $extension = new DoctrineExtension();
438
439
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
440
            ->addBaseSecondLevelCache()
441
            ->build();
442
443
        $extension->load(array($configurationArray), $container);
444
        $this->compileContainer($container);
445
446
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
447
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
448
        if (method_exists($definition, 'getFactory')) {
449
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
450
        } else {
451
            $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...
452
            $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...
453
        }
454
455
        $this->assertDICConstructorArguments($definition, array(
456
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
457
        ));
458
459
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
460
        $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass());
461
    }
462
463
    public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration()
464
    {
465
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
466
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
467
        }
468
        $container = $this->getContainer();
469
        $extension = new DoctrineExtension();
470
471
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
472
            ->addSecondLevelCache([
473
                'region_cache_driver' => [
474
                    'type' => 'memcache'],
475
                'regions' => [
476
                    'hour_region' => [
477
                        'lifetime' => 3600
478
                    ]
479
                ],
480
                'factory' => 'YamlBundle\Cache\MyCacheFactory',
481
            ])
482
            ->build();
483
484
        $extension->load(array($configurationArray), $container);
485
        $this->compileContainer($container);
486
487
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
488
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
489 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...
490
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
491
        } else {
492
            $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...
493
            $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...
494
        }
495
496
        $this->assertDICConstructorArguments($definition, array(
497
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
498
        ));
499
500
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
501
        $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass());
502
    }
503
504 View Code Duplication
    public function testBundleEntityAliases()
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...
505
    {
506
        $container = $this->getContainer();
507
        $extension = new DoctrineExtension();
508
509
        $config = BundleConfigurationBuilder::createBuilder()
510
             ->addBaseConnection()
511
             ->build();
512
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))));
513
        $extension->load(array($config), $container);
514
515
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
516
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
517
            array(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'))
518
        );
519
    }
520
521 View Code Duplication
    public function testOverwriteEntityAliases()
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...
522
    {
523
        $container = $this->getContainer();
524
        $extension = new DoctrineExtension();
525
526
        $config = BundleConfigurationBuilder::createBuilder()
527
             ->addBaseConnection()
528
             ->build();
529
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array('alias' => 'yml')))));
530
        $extension->load(array($config), $container);
531
532
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
533
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
534
            array(array('yml' => 'Fixtures\Bundles\YamlBundle\Entity'))
535
        );
536
    }
537
538
    public function testYamlBundleMappingDetection()
539
    {
540
        $container = $this->getContainer('YamlBundle');
541
        $extension = new DoctrineExtension();
542
543
        $config = BundleConfigurationBuilder::createBuilder()
544
            ->addBaseConnection()
545
            ->addBaseEntityManager()
546
            ->build();
547
        $extension->load(array($config), $container);
548
549
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
550
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
551
            new Reference('doctrine.orm.default_yml_metadata_driver'),
552
            'Fixtures\Bundles\YamlBundle\Entity',
553
        ));
554
    }
555
556 View Code Duplication
    public function testXmlBundleMappingDetection()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
557
    {
558
        $container = $this->getContainer('XmlBundle');
559
        $extension = new DoctrineExtension();
560
561
        $config = BundleConfigurationBuilder::createBuilder()
562
            ->addBaseConnection()
563
            ->addEntityManager(array(
564
                'default_entity_manager' => 'default',
565
                'entity_managers' => array(
566
                    'default' => array(
567
                        'mappings' => array(
568
                            'XmlBundle' => array()
569
                        )
570
                    )
571
                )
572
            ))
573
            ->build();
574
        $extension->load(array($config), $container);
575
576
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
577
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
578
            new Reference('doctrine.orm.default_xml_metadata_driver'),
579
            'Fixtures\Bundles\XmlBundle\Entity',
580
        ));
581
    }
582
583 View Code Duplication
    public function testAnnotationsBundleMappingDetection()
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...
584
    {
585
        $container = $this->getContainer('AnnotationsBundle');
586
        $extension = new DoctrineExtension();
587
588
        $config = BundleConfigurationBuilder::createBuilder()
589
            ->addBaseConnection()
590
            ->addEntityManager(array(
591
                'default_entity_manager' => 'default',
592
                'entity_managers' => array(
593
                    'default' => array(
594
                        'mappings' => array(
595
                            'AnnotationsBundle' => array()
596
                        )
597
                    )
598
                )
599
            ))
600
            ->build();
601
        $extension->load(array($config), $container);
602
603
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
604
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
605
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
606
            'Fixtures\Bundles\AnnotationsBundle\Entity',
607
        ));
608
    }
609
610
    public function testOrmMergeConfigs()
611
    {
612
        $container = $this->getContainer(array('XmlBundle', 'AnnotationsBundle'));
0 ignored issues
show
Documentation introduced by
array('XmlBundle', 'AnnotationsBundle') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
613
        $extension = new DoctrineExtension();
614
615
        $config1 = BundleConfigurationBuilder::createBuilder()
616
            ->addBaseConnection()
617
            ->addEntityManager(array(
618
                'auto_generate_proxy_classes' => true,
619
                'default_entity_manager' => 'default',
620
                'entity_managers' => array(
621
                    'default' => array(
622
                        'mappings' => array(
623
                            'AnnotationsBundle' => array()
624
                        )
625
                    ),
626
                ),
627
            ))
628
            ->build();
629
        $config2 = BundleConfigurationBuilder::createBuilder()
630
            ->addBaseConnection()
631
            ->addEntityManager(array(
632
                'auto_generate_proxy_classes' => false,
633
                'default_entity_manager' => 'default',
634
                'entity_managers' => array(
635
                    'default' => array(
636
                        'mappings' => array(
637
                            'XmlBundle' => array()
638
                        )
639
                    ),
640
                ),
641
            ))
642
            ->build();
643
        $extension->load(array($config1, $config2), $container);
644
645
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
646
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', array(
647
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
648
            'Fixtures\Bundles\AnnotationsBundle\Entity',
649
        ));
650
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', array(
651
            new Reference('doctrine.orm.default_xml_metadata_driver'),
652
            'Fixtures\Bundles\XmlBundle\Entity',
653
        ));
654
655
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
656
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses');
657
658
        $calls = $configDef->getMethodCalls();
659
        foreach ($calls as $call) {
660
            if ($call[0] === 'setAutoGenerateProxyClasses') {
661
                $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0]));
662
                break;
663
            }
664
        }
665
    }
666
667
    public function testAnnotationsBundleMappingDetectionWithVendorNamespace()
668
    {
669
        $container = $this->getContainer('AnnotationsBundle', 'Vendor');
670
        $extension = new DoctrineExtension();
671
672
        $config = BundleConfigurationBuilder::createBuilder()
673
            ->addBaseConnection()
674
            ->addEntityManager(array(
675
                'default_entity_manager' => 'default',
676
                'entity_managers' => array(
677
                    'default' => array(
678
                        'mappings' => array(
679
                            'AnnotationsBundle' => array()
680
                        )
681
                    )
682
                )
683
            ))
684
            ->build();
685
        $extension->load(array($config), $container);
686
687
        $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls();
688
        $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]);
689
        $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]);
690
    }
691
692
    public function testCacheConfiguration()
693
    {
694
        $container = $this->getContainer();
695
        $extension = new DoctrineExtension();
696
697
        $config = BundleConfigurationBuilder::createBuilder()
698
             ->addBaseConnection()
699
             ->addEntityManager(array(
700
                 'metadata_cache_driver' => array(
701
                     'cache_provider' => 'metadata_cache',
702
                 ),
703
                 'query_cache_driver' => array(
704
                     'cache_provider' => 'query_cache',
705
                 ),
706
                 'result_cache_driver' => array(
707
                     'cache_provider' => 'result_cache',
708
                 ),
709
             ))
710
            ->build();
711
712
        $extension->load(array($config), $container);
713
714
        $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache'));
715
        $alias = $container->getAlias('doctrine.orm.default_metadata_cache');
716
        $this->assertEquals('doctrine_cache.providers.metadata_cache', (string) $alias);
717
718
        $this->assertTrue($container->hasAlias('doctrine.orm.default_query_cache'));
719
        $alias = $container->getAlias('doctrine.orm.default_query_cache');
720
        $this->assertEquals('doctrine_cache.providers.query_cache', (string) $alias);
721
722
        $this->assertTrue($container->hasAlias('doctrine.orm.default_result_cache'));
723
        $alias = $container->getAlias('doctrine.orm.default_result_cache');
724
        $this->assertEquals('doctrine_cache.providers.result_cache', (string) $alias);
725
    }
726
727
    public function testShardManager()
728
    {
729
        $container = $this->getContainer();
730
        $extension = new DoctrineExtension();
731
732
        $config = BundleConfigurationBuilder::createBuilder()
733
             ->addConnection(array(
734
                 'connections' => array(
735
                     'foo' => array(
736
                         'shards' => array(
737
                             'test' => array('id' => 1)
738
                         ),
739
                     ),
740
                     'bar' => array(),
741
                 ),
742
             ))
743
            ->build();
744
745
        $extension->load(array($config), $container);
746
747
        $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager'));
748
        $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager'));
749
    }
750
751
    private function getContainer($bundles = 'YamlBundle', $vendor = null)
752
    {
753
        $bundles = (array) $bundles;
754
755
        $map = array();
756
        foreach ($bundles as $bundle) {
757
            require_once __DIR__.'/Fixtures/Bundles/'.($vendor ? $vendor.'/' : '').$bundle.'/'.$bundle.'.php';
758
759
            $map[$bundle] = 'Fixtures\\Bundles\\'.($vendor ? $vendor.'\\' : '').$bundle.'\\'.$bundle;
760
        }
761
762
        return new ContainerBuilder(new ParameterBag(array(
763
            'kernel.name' => 'app',
764
            'kernel.debug' => false,
765
            'kernel.bundles' => $map,
766
            'kernel.cache_dir' => sys_get_temp_dir(),
767
            'kernel.environment' => 'test',
768
            'kernel.root_dir' => __DIR__.'/../../', // src dir
769
        )));
770
    }
771
772
    private function assertDICConstructorArguments(Definition $definition, array $args)
773
    {
774
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '".$definition->getClass()."' don't match.");
775
    }
776
777 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...
778
    {
779
        $calls = $definition->getMethodCalls();
780
        if (isset($calls[$pos][0])) {
781
            $this->assertEquals($methodName, $calls[$pos][0], "Method '".$methodName."' is expected to be called at position $pos.");
782
783
            if ($params !== null) {
784
                $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
785
            }
786
        }
787
    }
788
789
    /**
790
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
791
     *
792
     * @param Definition $definition
793
     * @param string     $methodName
794
     * @param array|null $params
795
     */
796 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...
797
    {
798
        $calls = $definition->getMethodCalls();
799
        $called = false;
800
        foreach ($calls as $call) {
801
            if ($call[0] === $methodName) {
802
                if ($called) {
803
                    $this->fail("Method '".$methodName."' is expected to be called only once, a second call was registered though.");
804
                } else {
805
                    $called = true;
806
                    if ($params !== null) {
807
                        $this->assertEquals($params, $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
808
                    }
809
                }
810
            }
811
        }
812
        if (!$called) {
813
            $this->fail("Method '".$methodName."' is expected to be called once, definition does not contain a call though.");
814
        }
815
    }
816
817
    private function compileContainer(ContainerBuilder $container)
818
    {
819
        $container->getCompilerPassConfig()->setOptimizationPasses(array(class_exists(ResolveChildDefinitionsPass::class) ? new ResolveChildDefinitionsPass() : new ResolveDefinitionTemplatesPass()));
0 ignored issues
show
Documentation introduced by
array(class_exists(\Symf...initionTemplatesPass()) is of type array<integer,object<Sym...nitionTemplatesPass>"}>, but the function expects a array<integer,object<Sym...CompilerPassInterface>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
820
        $container->getCompilerPassConfig()->setRemovingPasses(array());
821
        $container->compile();
822
    }
823
824
}
825
826
class TestWrapperClass extends Connection {}
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
827