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