Completed
Pull Request — master (#685)
by Christophe
02:00
created

DoctrineExtensionTest::testAutowiringAlias()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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