Completed
Pull Request — master (#805)
by
unknown
05:39
created

testXmlBundleMappingDetection()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 17

Duplication

Lines 26
Ratio 100 %

Importance

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

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
806
        $container->getCompilerPassConfig()->setRemovingPasses([]);
807
        $container->compile();
808
    }
809
}
810
811
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...
812
{
813
}
814