Completed
Pull Request — master (#601)
by Mike
02:22
created

DoctrineExtensionTest::testOrmMergeConfigs()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 56
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 56
rs 9.7251
c 0
b 0
f 0
cc 3
eloc 38
nc 3
nop 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
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\Proxy\AbstractProxyFactory;
20
use Doctrine\ORM\Version;
21
use Symfony\Component\DependencyInjection\ContainerBuilder;
22
use Symfony\Component\DependencyInjection\Definition;
23
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
24
use Symfony\Component\DependencyInjection\Reference;
25
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
26
27
class DoctrineExtensionTest extends \PHPUnit_Framework_TestCase
28
{
29
30
    public function testDbalGenerateDefaultConnectionConfiguration()
31
    {
32
        $container = $this->getContainer();
33
        $extension = new DoctrineExtension();
34
35
        $container->registerExtension($extension);
36
37
        $extension->load(array(array('dbal' => array())), $container);
38
39
        // doctrine.dbal.default_connection
40
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3));
41
        $this->assertEquals('default', $container->getParameter('doctrine.default_connection'));
42
        $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']);
43
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']);
44
        $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']);
45
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']);
46
        $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']);
47
        $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']);
48
    }
49
50
    public function testDbalOverrideDefaultConnection()
51
    {
52
        $container = $this->getContainer();
53
        $extension = new DoctrineExtension();
54
55
        $container->registerExtension($extension);
56
57
        $extension->load(array(array(), array('dbal' => array('default_connection' => 'foo')), array()), $container);
58
59
        // doctrine.dbal.default_connection
60
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options');
61
        $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options');
62
    }
63
64
    /**
65
     * @expectedException \LogicException
66
     * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well.
67
     */
68
    public function testOrmRequiresDbal()
69
    {
70
        $extension = new DoctrineExtension();
71
72
        $extension->load(array(array('orm' => array('auto_mapping' => true))), $this->getContainer());
73
    }
74
75
    public function getAutomappingConfigurations()
76
    {
77
        return array(
78
            array(
79
                array(
80
                    'em1' => array(
81
                        'mappings' => array(
82
                            'YamlBundle' => null,
83
                        ),
84
                    ),
85
                    'em2' => array(
86
                        'mappings' => array(
87
                            'XmlBundle' => null,
88
                        ),
89
                    ),
90
                ),
91
            ),
92
            array(
93
                array(
94
                    'em1' => array(
95
                        'auto_mapping' => true,
96
                    ),
97
                    'em2' => array(
98
                        'mappings' => array(
99
                            'XmlBundle' => null,
100
                        ),
101
                    ),
102
                ),
103
            ),
104
            array(
105
                array(
106
                    'em1' => array(
107
                        'auto_mapping' => true,
108
                        'mappings' => array(
109
                            'YamlBundle' => null,
110
                        ),
111
                    ),
112
                    'em2' => array(
113
                        'mappings' => array(
114
                            'XmlBundle' => null,
115
                        ),
116
                    ),
117
                ),
118
            ),
119
        );
120
    }
121
122
    /**
123
     * @dataProvider getAutomappingConfigurations
124
     */
125
    public function testAutomapping(array $entityManagers)
126
    {
127
        $extension = new DoctrineExtension();
128
129
        if (!method_exists($extension, 'fixManagersAutoMappings')) {
130
            $this->markTestSkipped('Auto mapping with multiple managers available with Symfony ~2.6');
131
        }
132
133
        $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...
134
            'YamlBundle',
135
            'XmlBundle',
136
        ));
137
138
        $extension->load(
139
            array(
140
                array(
141
                    'dbal' => array(
142
                        'default_connection' => 'cn1',
143
                        'connections' => array(
144
                            'cn1' => array(),
145
                            'cn2' => array(),
146
                        ),
147
                    ),
148
                    'orm' => array(
149
                        'entity_managers' => $entityManagers,
150
                    ),
151
                ),
152
            ), $container);
153
154
        $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration');
155
        $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration');
156
157
        $this->assertContains(
158
            array(
159
                'setEntityNamespaces',
160
                array(
161
                    array(
162
                        'YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity',
163
                    ),
164
                ),
165
            ),
166
            $configEm1->getMethodCalls()
167
        );
168
169
        $this->assertContains(
170
            array(
171
                'setEntityNamespaces',
172
                array(
173
                    array(
174
                        'XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity',
175
                    ),
176
                ),
177
            ),
178
            $configEm2->getMethodCalls()
179
        );
180
    }
181
182
    public function testDbalLoad()
183
    {
184
        $container = $this->getContainer();
185
        $extension = new DoctrineExtension();
186
187
        $extension->load(array(
188
            array('dbal' => array('connections' => array('default' => array('password' => 'foo')))),
189
            array(),
190
            array('dbal' => array('default_connection' => 'foo')),
191
            array()), $container);
192
193
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
194
195
        $this->assertEquals('foo', $config['password']);
196
        $this->assertEquals('root', $config['user']);
197
    }
198
199
    public function testDependencyInjectionConfigurationDefaults()
200
    {
201
        $container = $this->getContainer();
202
        $extension = new DoctrineExtension();
203
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
204
205
        $extension->load(array($config), $container);
206
207
        $this->assertFalse($container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
208
        $this->assertEquals('Doctrine\ORM\Configuration', $container->getParameter('doctrine.orm.configuration.class'));
209
        $this->assertEquals('Doctrine\ORM\EntityManager', $container->getParameter('doctrine.orm.entity_manager.class'));
210
        $this->assertEquals('Proxies', $container->getParameter('doctrine.orm.proxy_namespace'));
211
        $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.orm.cache.array.class'));
212
        $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.orm.cache.apc.class'));
213
        $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.orm.cache.memcache.class'));
214
        $this->assertEquals('localhost', $container->getParameter('doctrine.orm.cache.memcache_host'));
215
        $this->assertEquals('11211', $container->getParameter('doctrine.orm.cache.memcache_port'));
216
        $this->assertEquals('Memcache', $container->getParameter('doctrine.orm.cache.memcache_instance.class'));
217
        $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.orm.cache.xcache.class'));
218
        $this->assertEquals('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->getParameter('doctrine.orm.metadata.driver_chain.class'));
219
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.orm.metadata.annotation.class'));
220
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver', $container->getParameter('doctrine.orm.metadata.xml.class'));
221
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver', $container->getParameter('doctrine.orm.metadata.yml.class'));
222
223
        // second-level cache
224
        $this->assertEquals('Doctrine\ORM\Cache\DefaultCacheFactory', $container->getParameter('doctrine.orm.second_level_cache.default_cache_factory.class'));
225
        $this->assertEquals('Doctrine\ORM\Cache\Region\DefaultRegion', $container->getParameter('doctrine.orm.second_level_cache.default_region.class'));
226
        $this->assertEquals('Doctrine\ORM\Cache\Region\FileLockRegion', $container->getParameter('doctrine.orm.second_level_cache.filelock_region.class'));
227
        $this->assertEquals('Doctrine\ORM\Cache\Logging\CacheLoggerChain', $container->getParameter('doctrine.orm.second_level_cache.logger_chain.class'));
228
        $this->assertEquals('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger', $container->getParameter('doctrine.orm.second_level_cache.logger_statistics.class'));
229
        $this->assertEquals('Doctrine\ORM\Cache\CacheConfiguration', $container->getParameter('doctrine.orm.second_level_cache.cache_configuration.class'));
230
        $this->assertEquals('Doctrine\ORM\Cache\RegionsConfiguration', $container->getParameter('doctrine.orm.second_level_cache.regions_configuration.class'));
231
232
233
        $config = BundleConfigurationBuilder::createBuilder()
234
            ->addBaseConnection()
235
            ->addEntityManager(array(
236
                'proxy_namespace' => 'MyProxies',
237
                'auto_generate_proxy_classes' => true,
238
                'default_entity_manager' => 'default',
239
                'entity_managers' => array(
240
                    'default' => array(
241
                        'mappings' => array('YamlBundle' => array()),
242
                    ),
243
                ),
244
            ))
245
            ->build();
246
247
        $container = $this->getContainer();
248
        $extension->load(array($config), $container);
249
        $this->compileContainer($container);
250
251
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
252
253
        $args = $definition->getArguments();
254
        $this->assertEquals('pdo_mysql', $args[0]['driver']);
255
        $this->assertEquals('localhost', $args[0]['host']);
256
        $this->assertEquals('root', $args[0]['user']);
257
        $this->assertEquals('doctrine.dbal.default_connection.configuration', (string) $args[1]);
258
        $this->assertEquals('doctrine.dbal.default_connection.event_manager', (string) $args[2]);
259
        $this->assertCount(0, $definition->getMethodCalls());
260
261
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
262
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
263 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...
264
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
265
        } else {
266
            $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...
267
            $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...
268
        }
269
270
        $this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $container->getParameter('doctrine.entity_managers'), "Set of the existing EntityManagers names is incorrect.");
271
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), "Set of the existing EntityManagers names is incorrect.");
272
273
        $arguments = $definition->getArguments();
274
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
275
        $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]);
276
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
277
        $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]);
278
279
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
280
        $calls = array_values($definition->getMethodCalls());
281
        $this->assertEquals(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'), $calls[0][1][0]);
282
        $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]);
283
        $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]);
284
        $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]);
285
286
        if (version_compare(Version::VERSION, "2.3.0-DEV") >= 0) {
287
            $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]);
288
            $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]);
289
        }
290
        if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) {
291
            $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]);
292
        }
293
294
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache'));
295
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
296
297
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_query_cache'));
298
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
299
300
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_result_cache'));
301
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
302
    }
303
304
    public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection()
305
    {
306
        $container = $this->getContainer();
307
        $extension = new DoctrineExtension();
308
309
        $extension->load(array(array('dbal' => array('connections' => array(
310
            'default' => array('password' => 'foo', 'use_savepoints' => true)
311
        )))), $container);
312
313
        $calls = $container->getDefinition('doctrine.dbal.default_connection')->getMethodCalls();
314
        $this->assertCount(1, $calls);
315
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
316
        $this->assertTrue($calls[0][1][0]);
317
    }
318
319
    public function testAutoGenerateProxyClasses()
320
    {
321
        $container = $this->getContainer();
322
        $extension = new DoctrineExtension();
323
324
        $config = BundleConfigurationBuilder::createBuilder()
325
            ->addBaseConnection()
326
            ->addEntityManager(array(
327
                'proxy_namespace' => 'MyProxies',
328
                'auto_generate_proxy_classes' => 'eval',
329
                'default_entity_manager' => 'default',
330
                'entity_managers' => array(
331
                    'default' => array(
332
                        'mappings' => array('YamlBundle' => array()),
333
                    ),
334
                ),
335
            ))
336
            ->build();
337
338
        $extension->load(array($config), $container);
339
340
        $this->assertEquals(AbstractProxyFactory::AUTOGENERATE_EVAL, $container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
341
    }
342
343
    public function testSingleEntityManagerWithDefaultConfiguration()
344
    {
345
        $container = $this->getContainer();
346
        $extension = new DoctrineExtension();
347
348
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
349
350
        $extension->load(array($configurationArray), $container);
351
        $this->compileContainer($container);
352
353
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
354
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
355 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...
356
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
357
        } else {
358
            $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...
359
            $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...
360
        }
361
362
        $this->assertDICConstructorArguments($definition, array(
363
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
364
        ));
365
    }
366
367
    public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration()
368
    {
369
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
370
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
371
        }
372
        $container = $this->getContainer();
373
        $extension = new DoctrineExtension();
374
375
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
376
            ->addBaseSecondLevelCache()
377
            ->build();
378
379
        $extension->load(array($configurationArray), $container);
380
        $this->compileContainer($container);
381
382
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
383
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
384
        if (method_exists($definition, 'getFactory')) {
385
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
386
        } else {
387
            $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...
388
            $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...
389
        }
390
391
        $this->assertDICConstructorArguments($definition, array(
392
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
393
        ));
394
395
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
396
        $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass());
397
    }
398
399
    public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration()
400
    {
401
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
402
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
403
        }
404
        $container = $this->getContainer();
405
        $extension = new DoctrineExtension();
406
407
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
408
            ->addSecondLevelCache([
409
                'region_cache_driver' => [
410
                    'type' => 'memcache'],
411
                'regions' => [
412
                    'hour_region' => [
413
                        'lifetime' => 3600
414
                    ]
415
                ],
416
                'factory' => 'YamlBundle\Cache\MyCacheFactory',
417
            ])
418
            ->build();
419
420
        $extension->load(array($configurationArray), $container);
421
        $this->compileContainer($container);
422
423
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
424
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
425 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...
426
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
427
        } else {
428
            $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...
429
            $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...
430
        }
431
432
        $this->assertDICConstructorArguments($definition, array(
433
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
434
        ));
435
436
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
437
        $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass());
438
    }
439
440 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...
441
    {
442
        $container = $this->getContainer();
443
        $extension = new DoctrineExtension();
444
445
        $config = BundleConfigurationBuilder::createBuilder()
446
             ->addBaseConnection()
447
             ->build();
448
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))));
449
        $extension->load(array($config), $container);
450
451
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
452
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
453
            array(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'))
454
        );
455
    }
456
457 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...
458
    {
459
        $container = $this->getContainer();
460
        $extension = new DoctrineExtension();
461
462
        $config = BundleConfigurationBuilder::createBuilder()
463
             ->addBaseConnection()
464
             ->build();
465
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array('alias' => 'yml')))));
466
        $extension->load(array($config), $container);
467
468
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
469
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
470
            array(array('yml' => 'Fixtures\Bundles\YamlBundle\Entity'))
471
        );
472
    }
473
474
    public function testYamlBundleMappingDetection()
475
    {
476
        $container = $this->getContainer('YamlBundle');
477
        $extension = new DoctrineExtension();
478
479
        $config = BundleConfigurationBuilder::createBuilder()
480
            ->addBaseConnection()
481
            ->addBaseEntityManager()
482
            ->build();
483
        $extension->load(array($config), $container);
484
485
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
486
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
487
            new Reference('doctrine.orm.default_yml_metadata_driver'),
488
            'Fixtures\Bundles\YamlBundle\Entity',
489
        ));
490
    }
491
492 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...
493
    {
494
        $container = $this->getContainer('XmlBundle');
495
        $extension = new DoctrineExtension();
496
497
        $config = BundleConfigurationBuilder::createBuilder()
498
            ->addBaseConnection()
499
            ->addEntityManager(array(
500
                'default_entity_manager' => 'default',
501
                'entity_managers' => array(
502
                    'default' => array(
503
                        'mappings' => array(
504
                            'XmlBundle' => array()
505
                        )
506
                    )
507
                )
508
            ))
509
            ->build();
510
        $extension->load(array($config), $container);
511
512
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
513
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
514
            new Reference('doctrine.orm.default_xml_metadata_driver'),
515
            'Fixtures\Bundles\XmlBundle\Entity',
516
        ));
517
    }
518
519 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...
520
    {
521
        $container = $this->getContainer('AnnotationsBundle');
522
        $extension = new DoctrineExtension();
523
524
        $config = BundleConfigurationBuilder::createBuilder()
525
            ->addBaseConnection()
526
            ->addEntityManager(array(
527
                'default_entity_manager' => 'default',
528
                'entity_managers' => array(
529
                    'default' => array(
530
                        'mappings' => array(
531
                            'AnnotationsBundle' => array()
532
                        )
533
                    )
534
                )
535
            ))
536
            ->build();
537
        $extension->load(array($config), $container);
538
539
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
540
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
541
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
542
            'Fixtures\Bundles\AnnotationsBundle\Entity',
543
        ));
544
    }
545
546
    public function testOrmMergeConfigs()
547
    {
548
        $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...
549
        $extension = new DoctrineExtension();
550
551
        $config1 = BundleConfigurationBuilder::createBuilder()
552
            ->addBaseConnection()
553
            ->addEntityManager(array(
554
                'auto_generate_proxy_classes' => true,
555
                'default_entity_manager' => 'default',
556
                'entity_managers' => array(
557
                    'default' => array(
558
                        'mappings' => array(
559
                            'AnnotationsBundle' => array()
560
                        )
561
                    ),
562
                ),
563
            ))
564
            ->build();
565
        $config2 = BundleConfigurationBuilder::createBuilder()
566
            ->addBaseConnection()
567
            ->addEntityManager(array(
568
                'auto_generate_proxy_classes' => false,
569
                'default_entity_manager' => 'default',
570
                'entity_managers' => array(
571
                    'default' => array(
572
                        'mappings' => array(
573
                            'XmlBundle' => array()
574
                        )
575
                    ),
576
                ),
577
            ))
578
            ->build();
579
        $extension->load(array($config1, $config2), $container);
580
581
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
582
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', array(
583
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
584
            'Fixtures\Bundles\AnnotationsBundle\Entity',
585
        ));
586
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', array(
587
            new Reference('doctrine.orm.default_xml_metadata_driver'),
588
            'Fixtures\Bundles\XmlBundle\Entity',
589
        ));
590
591
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
592
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses');
593
594
        $calls = $configDef->getMethodCalls();
595
        foreach ($calls as $call) {
596
            if ($call[0] === 'setAutoGenerateProxyClasses') {
597
                $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0]));
598
                break;
599
            }
600
        }
601
    }
602
603
    public function testAnnotationsBundleMappingDetectionWithVendorNamespace()
604
    {
605
        $container = $this->getContainer('AnnotationsBundle', 'Vendor');
606
        $extension = new DoctrineExtension();
607
608
        $config = BundleConfigurationBuilder::createBuilder()
609
            ->addBaseConnection()
610
            ->addEntityManager(array(
611
                'default_entity_manager' => 'default',
612
                'entity_managers' => array(
613
                    'default' => array(
614
                        'mappings' => array(
615
                            'AnnotationsBundle' => array()
616
                        )
617
                    )
618
                )
619
            ))
620
            ->build();
621
        $extension->load(array($config), $container);
622
623
        $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls();
624
        $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]);
625
        $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]);
626
    }
627
628
    public function testCacheConfiguration()
629
    {
630
        $container = $this->getContainer();
631
        $extension = new DoctrineExtension();
632
633
        $config = BundleConfigurationBuilder::createBuilder()
634
             ->addBaseConnection()
635
             ->addEntityManager(array(
636
                 'metadata_cache_driver' => array(
637
                     'cache_provider' => 'metadata_cache',
638
                 ),
639
                 'query_cache_driver' => array(
640
                     'cache_provider' => 'query_cache',
641
                 ),
642
                 'result_cache_driver' => array(
643
                     'cache_provider' => 'result_cache',
644
                 ),
645
             ))
646
            ->build();
647
648
        $extension->load(array($config), $container);
649
650
        $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache'));
651
        $alias = $container->getAlias('doctrine.orm.default_metadata_cache');
652
        $this->assertEquals('doctrine_cache.providers.metadata_cache', (string) $alias);
653
654
        $this->assertTrue($container->hasAlias('doctrine.orm.default_query_cache'));
655
        $alias = $container->getAlias('doctrine.orm.default_query_cache');
656
        $this->assertEquals('doctrine_cache.providers.query_cache', (string) $alias);
657
658
        $this->assertTrue($container->hasAlias('doctrine.orm.default_result_cache'));
659
        $alias = $container->getAlias('doctrine.orm.default_result_cache');
660
        $this->assertEquals('doctrine_cache.providers.result_cache', (string) $alias);
661
    }
662
663
    public function testShardManager()
664
    {
665
        $container = $this->getContainer();
666
        $extension = new DoctrineExtension();
667
668
        $config = BundleConfigurationBuilder::createBuilder()
669
             ->addConnection(array(
670
                 'connections' => array(
671
                     'foo' => array(
672
                         'shards' => array(
673
                             'test' => array('id' => 1)
674
                         ),
675
                     ),
676
                     'bar' => array(),
677
                 ),
678
             ))
679
            ->build();
680
681
        $extension->load(array($config), $container);
682
683
        $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager'));
684
        $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager'));
685
    }
686
687
    private function getContainer($bundles = 'YamlBundle', $vendor = null)
688
    {
689
        $bundles = (array) $bundles;
690
691
        $map = array();
692
        foreach ($bundles as $bundle) {
693
            require_once __DIR__.'/Fixtures/Bundles/'.($vendor ? $vendor.'/' : '').$bundle.'/'.$bundle.'.php';
694
695
            $map[$bundle] = 'Fixtures\\Bundles\\'.($vendor ? $vendor.'\\' : '').$bundle.'\\'.$bundle;
696
        }
697
698
        return new ContainerBuilder(new ParameterBag(array(
699
            'kernel.debug' => false,
700
            'kernel.bundles' => $map,
701
            'kernel.cache_dir' => sys_get_temp_dir(),
702
            'kernel.environment' => 'test',
703
            'kernel.root_dir' => __DIR__.'/../../', // src dir
704
        )));
705
    }
706
707
    private function assertDICConstructorArguments(Definition $definition, array $args)
708
    {
709
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '".$definition->getClass()."' don't match.");
710
    }
711
712 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...
713
    {
714
        $calls = $definition->getMethodCalls();
715
        if (isset($calls[$pos][0])) {
716
            $this->assertEquals($methodName, $calls[$pos][0], "Method '".$methodName."' is expected to be called at position $pos.");
717
718
            if ($params !== null) {
719
                $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
720
            }
721
        }
722
    }
723
724
    /**
725
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
726
     *
727
     * @param Definition $definition
728
     * @param string     $methodName
729
     * @param array|null $params
730
     */
731 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...
732
    {
733
        $calls = $definition->getMethodCalls();
734
        $called = false;
735
        foreach ($calls as $call) {
736
            if ($call[0] === $methodName) {
737
                if ($called) {
738
                    $this->fail("Method '".$methodName."' is expected to be called only once, a second call was registered though.");
739
                } else {
740
                    $called = true;
741
                    if ($params !== null) {
742
                        $this->assertEquals($params, $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
743
                    }
744
                }
745
            }
746
        }
747
        if (!$called) {
748
            $this->fail("Method '".$methodName."' is expected to be called once, definition does not contain a call though.");
749
        }
750
    }
751
752
    private function compileContainer(ContainerBuilder $container)
753
    {
754
        $container->getCompilerPassConfig()->setOptimizationPasses(array(new ResolveDefinitionTemplatesPass()));
755
        $container->getCompilerPassConfig()->setRemovingPasses(array());
756
        $container->compile();
757
    }
758
759
}
760