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