Completed
Pull Request — master (#892)
by Andreas
01:57
created

testAnnotationsBundleMappingDetectionWithVendorNamespace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 9.536
cc 1
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\Persistence\ManagerRegistry;
8
use Doctrine\Common\Persistence\ObjectManager;
9
use Doctrine\Common\Proxy\AbstractProxyFactory;
10
use Doctrine\DBAL\Connection;
11
use Doctrine\DBAL\Driver\Connection as DriverConnection;
12
use Doctrine\ORM\EntityManagerInterface;
13
use Doctrine\ORM\Version;
14
use PHPUnit\Framework\TestCase;
15
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
16
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
17
use Symfony\Component\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\Definition;
19
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
20
use Symfony\Component\DependencyInjection\Reference;
21
use Symfony\Component\Messenger\MessageBusInterface;
22
23
class DoctrineExtensionTest extends TestCase
24
{
25
    public function testAutowiringAlias()
26
    {
27
        $container = $this->getContainer();
28
        $extension = new DoctrineExtension();
29
        $config    = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
30
31
        $extension->load([$config], $container);
32
33
        $expectedAliases = [
34
            DriverConnection::class => 'database_connection',
35
            Connection::class => 'database_connection',
36
            ManagerRegistry::class => 'doctrine',
37
            ObjectManager::class => 'doctrine.orm.entity_manager',
38
            EntityManagerInterface::class => 'doctrine.orm.entity_manager',
39
        ];
40
41
        foreach ($expectedAliases as $id => $target) {
42
            $this->assertTrue($container->hasAlias($id), sprintf('The container should have a `%s` alias for autowiring support.', $id));
43
44
            $alias = $container->getAlias($id);
45
            $this->assertEquals($target, (string) $alias, sprintf('The autowiring for `%s` should use `%s`.', $id, $target));
46
            $this->assertFalse($alias->isPublic(), sprintf('The autowiring alias for `%s` should be private.', $id, $target));
47
        }
48
    }
49
50
    public function testPublicServicesAndAliases()
51
    {
52
        $container = $this->getContainer();
53
        $extension = new DoctrineExtension();
54
        $config    = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
55
56
        $extension->load([$config], $container);
57
58
        $this->assertTrue($container->getDefinition('doctrine')->isPublic());
59
        $this->assertTrue($container->getAlias('doctrine.orm.entity_manager')->isPublic());
60
        $this->assertTrue($container->getAlias('database_connection')->isPublic());
61
    }
62
63
    public function testDbalGenerateDefaultConnectionConfiguration()
64
    {
65
        $container = $this->getContainer();
66
        $extension = new DoctrineExtension();
67
68
        $container->registerExtension($extension);
69
70
        $extension->load([['dbal' => []]], $container);
71
72
        // doctrine.dbal.default_connection
73
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3));
74
        $this->assertEquals('default', $container->getParameter('doctrine.default_connection'));
75
        $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']);
76
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']);
77
        $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']);
78
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']);
79
        $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']);
80
        $this->assertEquals([], $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']);
81
    }
82
83
    public function testDbalOverrideDefaultConnection()
84
    {
85
        $container = $this->getContainer();
86
        $extension = new DoctrineExtension();
87
88
        $container->registerExtension($extension);
89
90
        $extension->load([[], ['dbal' => ['default_connection' => 'foo']], []], $container);
91
92
        // doctrine.dbal.default_connection
93
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options');
94
        $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options');
95
    }
96
97
    /**
98
     * @expectedException \LogicException
99
     * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well.
100
     */
101
    public function testOrmRequiresDbal()
102
    {
103
        $extension = new DoctrineExtension();
104
105
        $extension->load([['orm' => ['auto_mapping' => true]]], $this->getContainer());
106
    }
107
108
    public function getAutomappingConfigurations()
109
    {
110
        return [
111
            [
112
                [
113
                    'em1' => [
114
                        'mappings' => ['YamlBundle' => null],
115
                    ],
116
                    'em2' => [
117
                        'mappings' => ['XmlBundle' => null],
118
                    ],
119
                ],
120
            ],
121
            [
122
                [
123
                    'em1' => ['auto_mapping' => true],
124
                    'em2' => [
125
                        'mappings' => ['XmlBundle' => null],
126
                    ],
127
                ],
128
            ],
129
            [
130
                [
131
                    'em1' => [
132
                        'auto_mapping' => true,
133
                        'mappings' => ['YamlBundle' => null],
134
                    ],
135
                    'em2' => [
136
                        'mappings' => ['XmlBundle' => null],
137
                    ],
138
                ],
139
            ],
140
        ];
141
    }
142
143
    /**
144
     * @dataProvider getAutomappingConfigurations
145
     */
146
    public function testAutomapping(array $entityManagers)
147
    {
148
        $extension = new DoctrineExtension();
149
150
        $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...
151
            'YamlBundle',
152
            'XmlBundle',
153
        ]);
154
155
        $extension->load(
156
            [
157
                [
158
                    'dbal' => [
159
                        'default_connection' => 'cn1',
160
                        'connections' => [
161
                            'cn1' => [],
162
                            'cn2' => [],
163
                        ],
164
                    ],
165
                    'orm' => ['entity_managers' => $entityManagers],
166
                ],
167
            ],
168
            $container
169
        );
170
171
        $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration');
172
        $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration');
173
174
        $this->assertContains(
175
            [
176
                'setEntityNamespaces',
177
                [
178
                    ['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'],
179
                ],
180
            ],
181
            $configEm1->getMethodCalls()
182
        );
183
184
        $this->assertContains(
185
            [
186
                'setEntityNamespaces',
187
                [
188
                    ['XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity'],
189
                ],
190
            ],
191
            $configEm2->getMethodCalls()
192
        );
193
    }
194
195
    public function testDbalLoad()
196
    {
197
        $container = $this->getContainer();
198
        $extension = new DoctrineExtension();
199
200
        $extension->load([
201
            ['dbal' => ['connections' => ['default' => ['password' => 'foo']]]],
202
            [],
203
            ['dbal' => ['default_connection' => 'foo']],
204
            [],
205
        ], $container);
206
207
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
208
209
        $this->assertEquals('foo', $config['password']);
210
        $this->assertEquals('root', $config['user']);
211
    }
212
213
    public function testDbalWrapperClass()
214
    {
215
        $container = $this->getContainer();
216
        $extension = new DoctrineExtension();
217
218
        $extension->load(
219
            [
220
                [
221
                    'dbal' => [
222
                        'connections' => [
223
                            'default' => ['password' => 'foo', 'wrapper_class' => TestWrapperClass::class],
224
                            'second' => ['password' => 'boo'],
225
                        ],
226
                    ],
227
                ],
228
                [],
229
                ['dbal' => ['default_connection' => 'foo']],
230
                [],
231
            ],
232
            $container
233
        );
234
235
        $this->assertEquals(TestWrapperClass::class, $container->getDefinition('doctrine.dbal.default_connection')->getClass());
236
        $this->assertNull($container->getDefinition('doctrine.dbal.second_connection')->getClass());
237
    }
238
239
    public function testDependencyInjectionConfigurationDefaults()
240
    {
241
        $container = $this->getContainer();
242
        $extension = new DoctrineExtension();
243
        $config    = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
244
245
        $extension->load([$config], $container);
246
247
        $this->assertFalse($container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
248
        $this->assertEquals('Doctrine\ORM\Configuration', $container->getParameter('doctrine.orm.configuration.class'));
249
        $this->assertEquals('Doctrine\ORM\EntityManager', $container->getParameter('doctrine.orm.entity_manager.class'));
250
        $this->assertEquals('Proxies', $container->getParameter('doctrine.orm.proxy_namespace'));
251
        $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.orm.cache.array.class'));
252
        $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.orm.cache.apc.class'));
253
        $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.orm.cache.memcache.class'));
254
        $this->assertEquals('localhost', $container->getParameter('doctrine.orm.cache.memcache_host'));
255
        $this->assertEquals('11211', $container->getParameter('doctrine.orm.cache.memcache_port'));
256
        $this->assertEquals('Memcache', $container->getParameter('doctrine.orm.cache.memcache_instance.class'));
257
        $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.orm.cache.xcache.class'));
258
        $this->assertEquals('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->getParameter('doctrine.orm.metadata.driver_chain.class'));
259
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.orm.metadata.annotation.class'));
260
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver', $container->getParameter('doctrine.orm.metadata.xml.class'));
261
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver', $container->getParameter('doctrine.orm.metadata.yml.class'));
262
263
        // second-level cache
264
        $this->assertEquals('Doctrine\ORM\Cache\DefaultCacheFactory', $container->getParameter('doctrine.orm.second_level_cache.default_cache_factory.class'));
265
        $this->assertEquals('Doctrine\ORM\Cache\Region\DefaultRegion', $container->getParameter('doctrine.orm.second_level_cache.default_region.class'));
266
        $this->assertEquals('Doctrine\ORM\Cache\Region\FileLockRegion', $container->getParameter('doctrine.orm.second_level_cache.filelock_region.class'));
267
        $this->assertEquals('Doctrine\ORM\Cache\Logging\CacheLoggerChain', $container->getParameter('doctrine.orm.second_level_cache.logger_chain.class'));
268
        $this->assertEquals('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger', $container->getParameter('doctrine.orm.second_level_cache.logger_statistics.class'));
269
        $this->assertEquals('Doctrine\ORM\Cache\CacheConfiguration', $container->getParameter('doctrine.orm.second_level_cache.cache_configuration.class'));
270
        $this->assertEquals('Doctrine\ORM\Cache\RegionsConfiguration', $container->getParameter('doctrine.orm.second_level_cache.regions_configuration.class'));
271
272
        $config = BundleConfigurationBuilder::createBuilder()
273
            ->addBaseConnection()
274
            ->addEntityManager([
275
                'proxy_namespace' => 'MyProxies',
276
                'auto_generate_proxy_classes' => true,
277
                'default_entity_manager' => 'default',
278
                'entity_managers' => [
279
                    'default' => [
280
                        'mappings' => ['YamlBundle' => []],
281
                    ],
282
                ],
283
            ])
284
            ->build();
285
286
        $container = $this->getContainer();
287
        $extension->load([$config], $container);
288
        $this->compileContainer($container);
289
290
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
291
292
        $args = $definition->getArguments();
293
        $this->assertEquals('pdo_mysql', $args[0]['driver']);
294
        $this->assertEquals('localhost', $args[0]['host']);
295
        $this->assertEquals('root', $args[0]['user']);
296
        $this->assertEquals('doctrine.dbal.default_connection.configuration', (string) $args[1]);
297
        $this->assertEquals('doctrine.dbal.default_connection.event_manager', (string) $args[2]);
298
        $this->assertCount(0, $definition->getMethodCalls());
0 ignored issues
show
Documentation introduced by
$definition->getMethodCalls() is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

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...
299
300
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
301
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
302
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
303
304
        $this->assertEquals(['default' => 'doctrine.orm.default_entity_manager'], $container->getParameter('doctrine.entity_managers'), 'Set of the existing EntityManagers names is incorrect.');
305
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), 'Set of the existing EntityManagers names is incorrect.');
306
307
        $arguments = $definition->getArguments();
308
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
309
        $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]);
310
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
311
        $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]);
312
313
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
314
        $calls      = array_values($definition->getMethodCalls());
315
        $this->assertEquals(['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'], $calls[0][1][0]);
316
        $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]);
317
        $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]);
318
        $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]);
319
320
        $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]);
321
        $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]);
322
        $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]);
323
324
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
325
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
326
327
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_query_cache'));
328
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
329
330
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_result_cache'));
331
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
332
    }
333
334
    public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection()
335
    {
336
        $container = $this->getContainer();
337
        $extension = new DoctrineExtension();
338
339
        $extension->load([[
340
            'dbal' => [
341
                'connections' => [
342
                    'default' => ['password' => 'foo', 'use_savepoints' => true],
343
                ],
344
            ],
345
        ],
346
        ], $container);
347
348
        $calls = $container->getDefinition('doctrine.dbal.default_connection')->getMethodCalls();
349
        $this->assertCount(1, $calls);
0 ignored issues
show
Documentation introduced by
$calls is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

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...
350
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
351
        $this->assertTrue($calls[0][1][0]);
352
    }
353
354
    public function testAutoGenerateProxyClasses()
355
    {
356
        $container = $this->getContainer();
357
        $extension = new DoctrineExtension();
358
359
        $config = BundleConfigurationBuilder::createBuilder()
360
            ->addBaseConnection()
361
            ->addEntityManager([
362
                'proxy_namespace' => 'MyProxies',
363
                'auto_generate_proxy_classes' => 'eval',
364
                'default_entity_manager' => 'default',
365
                'entity_managers' => [
366
                    'default' => [
367
                        'mappings' => ['YamlBundle' => []],
368
                    ],
369
                ],
370
            ])
371
            ->build();
372
373
        $extension->load([$config], $container);
374
375
        $this->assertEquals(AbstractProxyFactory::AUTOGENERATE_EVAL, $container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
376
    }
377
378
    public function testSingleEntityManagerWithDefaultConfiguration()
379
    {
380
        $container = $this->getContainer();
381
        $extension = new DoctrineExtension();
382
383
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
384
385
        $extension->load([$configurationArray], $container);
386
        $this->compileContainer($container);
387
388
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
389
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
390
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
391
392
        $this->assertDICConstructorArguments($definition, [
393
            new Reference('doctrine.dbal.default_connection'),
394
            new Reference('doctrine.orm.default_configuration'),
395
        ]);
396
    }
397
398
    public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration()
399
    {
400
        $container = $this->getContainer();
401
        $extension = new DoctrineExtension();
402
403
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
404
            ->addBaseSecondLevelCache()
405
            ->build();
406
407
        $extension->load([$configurationArray], $container);
408
        $this->compileContainer($container);
409
410
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
411
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
412
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
413
414
        $this->assertDICConstructorArguments($definition, [
415
            new Reference('doctrine.dbal.default_connection'),
416
            new Reference('doctrine.orm.default_configuration'),
417
        ]);
418
419
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
420
        $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass());
421
    }
422
423
    public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration()
424
    {
425
        $container = $this->getContainer();
426
        $extension = new DoctrineExtension();
427
428
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
429
            ->addSecondLevelCache([
430
                'region_cache_driver' => ['type' => 'memcache'],
431
                'regions' => [
432
                    'hour_region' => ['lifetime' => 3600],
433
                ],
434
                'factory' => 'YamlBundle\Cache\MyCacheFactory',
435
            ])
436
            ->build();
437
438
        $extension->load([$configurationArray], $container);
439
        $this->compileContainer($container);
440
441
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
442
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
443
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
444
445
        $this->assertDICConstructorArguments($definition, [
446
            new Reference('doctrine.dbal.default_connection'),
447
            new Reference('doctrine.orm.default_configuration'),
448
        ]);
449
450
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
451
        $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass());
452
    }
453
454 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...
455
    {
456
        $container = $this->getContainer();
457
        $extension = new DoctrineExtension();
458
459
        $config        = BundleConfigurationBuilder::createBuilder()
460
             ->addBaseConnection()
461
             ->build();
462
        $config['orm'] = ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['mappings' => ['YamlBundle' => []]]]];
463
        $extension->load([$config], $container);
464
465
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
466
        $this->assertDICDefinitionMethodCallOnce(
467
            $definition,
468
            'setEntityNamespaces',
469
            [['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity']]
470
        );
471
    }
472
473 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...
474
    {
475
        $container = $this->getContainer();
476
        $extension = new DoctrineExtension();
477
478
        $config        = BundleConfigurationBuilder::createBuilder()
479
             ->addBaseConnection()
480
             ->build();
481
        $config['orm'] = ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['mappings' => ['YamlBundle' => ['alias' => 'yml']]]]];
482
        $extension->load([$config], $container);
483
484
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
485
        $this->assertDICDefinitionMethodCallOnce(
486
            $definition,
487
            'setEntityNamespaces',
488
            [['yml' => 'Fixtures\Bundles\YamlBundle\Entity']]
489
        );
490
    }
491
492
    public function testYamlBundleMappingDetection()
493
    {
494
        $container = $this->getContainer('YamlBundle');
495
        $extension = new DoctrineExtension();
496
497
        $config = BundleConfigurationBuilder::createBuilder()
498
            ->addBaseConnection()
499
            ->addBaseEntityManager()
500
            ->build();
501
        $extension->load([$config], $container);
502
503
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
504
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
505
            new Reference('doctrine.orm.default_yml_metadata_driver'),
506
            'Fixtures\Bundles\YamlBundle\Entity',
507
        ]);
508
    }
509
510 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...
511
    {
512
        $container = $this->getContainer('XmlBundle');
513
        $extension = new DoctrineExtension();
514
515
        $config = BundleConfigurationBuilder::createBuilder()
516
            ->addBaseConnection()
517
            ->addEntityManager([
518
                'default_entity_manager' => 'default',
519
                'entity_managers' => [
520
                    'default' => [
521
                        'mappings' => [
522
                            'XmlBundle' => [],
523
                        ],
524
                    ],
525
                ],
526
            ])
527
            ->build();
528
        $extension->load([$config], $container);
529
530
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
531
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
532
            new Reference('doctrine.orm.default_xml_metadata_driver'),
533
            'Fixtures\Bundles\XmlBundle\Entity',
534
        ]);
535
    }
536
537 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...
538
    {
539
        $container = $this->getContainer('AnnotationsBundle');
540
        $extension = new DoctrineExtension();
541
542
        $config = BundleConfigurationBuilder::createBuilder()
543
            ->addBaseConnection()
544
            ->addEntityManager([
545
                'default_entity_manager' => 'default',
546
                'entity_managers' => [
547
                    'default' => [
548
                        'mappings' => [
549
                            'AnnotationsBundle' => [],
550
                        ],
551
                    ],
552
                ],
553
            ])
554
            ->build();
555
        $extension->load([$config], $container);
556
557
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
558
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
559
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
560
            'Fixtures\Bundles\AnnotationsBundle\Entity',
561
        ]);
562
    }
563
564
    public function testOrmMergeConfigs()
565
    {
566
        $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...
567
        $extension = new DoctrineExtension();
568
569
        $config1 = BundleConfigurationBuilder::createBuilder()
570
            ->addBaseConnection()
571
            ->addEntityManager([
572
                'auto_generate_proxy_classes' => true,
573
                'default_entity_manager' => 'default',
574
                'entity_managers' => [
575
                    'default' => [
576
                        'mappings' => [
577
                            'AnnotationsBundle' => [],
578
                        ],
579
                    ],
580
                ],
581
            ])
582
            ->build();
583
        $config2 = BundleConfigurationBuilder::createBuilder()
584
            ->addBaseConnection()
585
            ->addEntityManager([
586
                'auto_generate_proxy_classes' => false,
587
                'default_entity_manager' => 'default',
588
                'entity_managers' => [
589
                    'default' => [
590
                        'mappings' => [
591
                            'XmlBundle' => [],
592
                        ],
593
                    ],
594
                ],
595
            ])
596
            ->build();
597
        $extension->load([$config1, $config2], $container);
598
599
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
600
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [
601
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
602
            'Fixtures\Bundles\AnnotationsBundle\Entity',
603
        ]);
604
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [
605
            new Reference('doctrine.orm.default_xml_metadata_driver'),
606
            'Fixtures\Bundles\XmlBundle\Entity',
607
        ]);
608
609
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
610
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses');
611
612
        $calls = $configDef->getMethodCalls();
613
        foreach ($calls as $call) {
614
            if ($call[0] === 'setAutoGenerateProxyClasses') {
615
                $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0]));
616
                break;
617
            }
618
        }
619
    }
620
621
    public function testAnnotationsBundleMappingDetectionWithVendorNamespace()
622
    {
623
        $container = $this->getContainer('AnnotationsBundle', 'Vendor');
624
        $extension = new DoctrineExtension();
625
626
        $config = BundleConfigurationBuilder::createBuilder()
627
            ->addBaseConnection()
628
            ->addEntityManager([
629
                'default_entity_manager' => 'default',
630
                'entity_managers' => [
631
                    'default' => [
632
                        'mappings' => [
633
                            'AnnotationsBundle' => [],
634
                        ],
635
                    ],
636
                ],
637
            ])
638
            ->build();
639
        $extension->load([$config], $container);
640
641
        $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls();
642
        $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]);
643
        $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]);
644
    }
645
646
    public function testMessengerIntegration()
647
    {
648
        if (! interface_exists(MessageBusInterface::class)) {
649
            $this->markTestSkipped('Symfony Messenger component is not installed');
650
        }
651
652
        $container = $this->getContainer();
653
        $extension = new DoctrineExtension();
654
655
        $config = BundleConfigurationBuilder::createBuilder()
656
            ->addBaseConnection()
657
            ->addEntityManager([
658
                'default_entity_manager' => 'default',
659
                'entity_managers' => [
660
                    'default' => [],
661
                ],
662
            ])
663
            ->build();
664
        $extension->load([$config], $container);
665
666
        $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_transaction'));
667
        $this->assertCount(1, $middlewarePrototype->getArguments());
0 ignored issues
show
Documentation introduced by
$middlewarePrototype->getArguments() is of type array, but the function expects a object<Countable>|object...nit\Framework\iterable>.

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...
668
    }
669
670
    public function testCacheConfiguration()
671
    {
672
        $container = $this->getContainer();
673
        $extension = new DoctrineExtension();
674
675
        $config = BundleConfigurationBuilder::createBuilder()
676
             ->addBaseConnection()
677
             ->addEntityManager([
678
                 'metadata_cache_driver' => ['cache_provider' => 'metadata_cache'],
679
                 'query_cache_driver' => ['cache_provider' => 'query_cache'],
680
                 'result_cache_driver' => ['cache_provider' => 'result_cache'],
681
             ])
682
            ->build();
683
684
        $extension->load([$config], $container);
685
686
        $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache'));
687
        $alias = $container->getAlias('doctrine.orm.default_metadata_cache');
688
        $this->assertEquals('doctrine_cache.providers.metadata_cache', (string) $alias);
689
690
        $this->assertTrue($container->hasAlias('doctrine.orm.default_query_cache'));
691
        $alias = $container->getAlias('doctrine.orm.default_query_cache');
692
        $this->assertEquals('doctrine_cache.providers.query_cache', (string) $alias);
693
694
        $this->assertTrue($container->hasAlias('doctrine.orm.default_result_cache'));
695
        $alias = $container->getAlias('doctrine.orm.default_result_cache');
696
        $this->assertEquals('doctrine_cache.providers.result_cache', (string) $alias);
697
    }
698
699
    public function testShardManager()
700
    {
701
        $container = $this->getContainer();
702
        $extension = new DoctrineExtension();
703
704
        $config = BundleConfigurationBuilder::createBuilder()
705
             ->addConnection([
706
                 'connections' => [
707
                     'foo' => [
708
                         'shards' => [
709
                             'test' => ['id' => 1],
710
                         ],
711
                     ],
712
                     'bar' => [],
713
                 ],
714
             ])
715
            ->build();
716
717
        $extension->load([$config], $container);
718
719
        $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager'));
720
        $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager'));
721
    }
722
723
    private function getContainer($bundles = 'YamlBundle', $vendor = null)
724
    {
725
        $bundles = (array) $bundles;
726
727
        $map = [];
728
        foreach ($bundles as $bundle) {
729
            require_once __DIR__ . '/Fixtures/Bundles/' . ($vendor ? $vendor . '/' : '') . $bundle . '/' . $bundle . '.php';
730
731
            $map[$bundle] = 'Fixtures\\Bundles\\' . ($vendor ? $vendor . '\\' : '') . $bundle . '\\' . $bundle;
732
        }
733
734
        return new ContainerBuilder(new ParameterBag([
735
            'kernel.name' => 'app',
736
            'kernel.debug' => false,
737
            'kernel.bundles' => $map,
738
            'kernel.cache_dir' => sys_get_temp_dir(),
739
            'kernel.environment' => 'test',
740
            'kernel.root_dir' => __DIR__ . '/../../', // src dir
741
        ]));
742
    }
743
744
    private function assertDICConstructorArguments(Definition $definition, array $args)
745
    {
746
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match.");
747
    }
748
749 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...
750
    {
751
        $calls = $definition->getMethodCalls();
752
        if (! isset($calls[$pos][0])) {
753
            return;
754
        }
755
756
        $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.');
757
758
        if ($params === null) {
759
            return;
760
        }
761
762
        $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
763
    }
764
765
    /**
766
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
767
     *
768
     * @param string     $methodName
769
     * @param array|null $params
770
     */
771 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...
772
    {
773
        $calls  = $definition->getMethodCalls();
774
        $called = false;
775
        foreach ($calls as $call) {
776
            if ($call[0] !== $methodName) {
777
                continue;
778
            }
779
780
            if ($called) {
781
                $this->fail("Method '" . $methodName . "' is expected to be called only once, a second call was registered though.");
782
            } else {
783
                $called = true;
784
                if ($params !== null) {
785
                    $this->assertEquals($params, $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
786
                }
787
            }
788
        }
789
        if ($called) {
790
            return;
791
        }
792
793
        $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though.");
794
    }
795
796
    private function compileContainer(ContainerBuilder $container)
797
    {
798
        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
799
        $container->getCompilerPassConfig()->setRemovingPasses([]);
800
        $container->compile();
801
    }
802
}
803
804
class TestWrapperClass extends Connection
805
{
806
}
807