Completed
Pull Request — master (#772)
by Michael
02:09
created

DoctrineExtensionTest::testDbalWrapperClass()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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