Completed
Push — master ( 601d80...357a47 )
by Andreas
01:53 queued 10s
created

getAutomappingConfigurations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 34
rs 9.376
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 InvalidArgumentException;
14
use PHPUnit\Framework\TestCase;
15
use Symfony\Component\Cache\Adapter\ArrayAdapter;
16
use Symfony\Component\Cache\DoctrineProvider;
17
use Symfony\Component\DependencyInjection\Compiler\ResolveChildDefinitionsPass;
18
use Symfony\Component\DependencyInjection\ContainerBuilder;
19
use Symfony\Component\DependencyInjection\Definition;
20
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
21
use Symfony\Component\DependencyInjection\Reference;
22
use Symfony\Component\Messenger\MessageBusInterface;
23
24
class DoctrineExtensionTest extends TestCase
25
{
26
    public function testAutowiringAlias()
27
    {
28
        $container = $this->getContainer();
29
        $extension = new DoctrineExtension();
30
        $config    = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
31
32
        $extension->load([$config], $container);
33
34
        $expectedAliases = [
35
            DriverConnection::class => 'database_connection',
36
            Connection::class => 'database_connection',
37
            ManagerRegistry::class => 'doctrine',
38
            ObjectManager::class => 'doctrine.orm.entity_manager',
39
            EntityManagerInterface::class => 'doctrine.orm.entity_manager',
40
        ];
41
42
        foreach ($expectedAliases as $id => $target) {
43
            $this->assertTrue($container->hasAlias($id), sprintf('The container should have a `%s` alias for autowiring support.', $id));
44
45
            $alias = $container->getAlias($id);
46
            $this->assertEquals($target, (string) $alias, sprintf('The autowiring for `%s` should use `%s`.', $id, $target));
47
            $this->assertFalse($alias->isPublic(), sprintf('The autowiring alias for `%s` should be private.', $id, $target));
48
        }
49
    }
50
51
    public function testPublicServicesAndAliases()
52
    {
53
        $container = $this->getContainer();
54
        $extension = new DoctrineExtension();
55
        $config    = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
56
57
        $extension->load([$config], $container);
58
59
        $this->assertTrue($container->getDefinition('doctrine')->isPublic());
60
        $this->assertTrue($container->getAlias('doctrine.orm.entity_manager')->isPublic());
61
        $this->assertTrue($container->getAlias('database_connection')->isPublic());
62
    }
63
64
    public function testDbalGenerateDefaultConnectionConfiguration()
65
    {
66
        $container = $this->getContainer();
67
        $extension = new DoctrineExtension();
68
69
        $container->registerExtension($extension);
70
71
        $extension->load([['dbal' => []]], $container);
72
73
        // doctrine.dbal.default_connection
74
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3));
75
        $this->assertEquals('default', $container->getParameter('doctrine.default_connection'));
76
        $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']);
77
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']);
78
        $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']);
79
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']);
80
        $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']);
81
        $this->assertEquals([], $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']);
82
    }
83
84
    public function testDbalOverrideDefaultConnection()
85
    {
86
        $container = $this->getContainer();
87
        $extension = new DoctrineExtension();
88
89
        $container->registerExtension($extension);
90
91
        $extension->load([[], ['dbal' => ['default_connection' => 'foo']], []], $container);
92
93
        // doctrine.dbal.default_connection
94
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options');
95
        $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options');
96
    }
97
98
    /**
99
     * @expectedException \LogicException
100
     * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well.
101
     */
102
    public function testOrmRequiresDbal()
103
    {
104
        $extension = new DoctrineExtension();
105
106
        $extension->load([['orm' => ['auto_mapping' => true]]], $this->getContainer());
107
    }
108
109
    public function getAutomappingConfigurations()
110
    {
111
        return [
112
            [
113
                [
114
                    'em1' => [
115
                        'mappings' => ['YamlBundle' => null],
116
                    ],
117
                    'em2' => [
118
                        'mappings' => ['XmlBundle' => null],
119
                    ],
120
                ],
121
            ],
122
            [
123
                [
124
                    'em1' => ['auto_mapping' => true],
125
                    'em2' => [
126
                        'mappings' => ['XmlBundle' => null],
127
                    ],
128
                ],
129
            ],
130
            [
131
                [
132
                    'em1' => [
133
                        'auto_mapping' => true,
134
                        'mappings' => ['YamlBundle' => null],
135
                    ],
136
                    'em2' => [
137
                        'mappings' => ['XmlBundle' => null],
138
                    ],
139
                ],
140
            ],
141
        ];
142
    }
143
144
    /**
145
     * @dataProvider getAutomappingConfigurations
146
     */
147
    public function testAutomapping(array $entityManagers)
148
    {
149
        $extension = new DoctrineExtension();
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());
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...
300
301
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
302
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
303
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
304
305
        $this->assertEquals(['default' => 'doctrine.orm.default_entity_manager'], $container->getParameter('doctrine.entity_managers'), 'Set of the existing EntityManagers names is incorrect.');
306
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), 'Set of the existing EntityManagers names is incorrect.');
307
308
        $arguments = $definition->getArguments();
309
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
310
        $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]);
311
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
312
        $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]);
313
314
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
315
        $calls      = array_values($definition->getMethodCalls());
316
        $this->assertEquals(['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'], $calls[0][1][0]);
317
        $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]);
318
        $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]);
319
        $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]);
320
321
        $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]);
322
        $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]);
323
        $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]);
324
325
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_metadata_cache'));
326
        $this->assertEquals(DoctrineProvider::class, $definition->getClass());
327
        $arguments = $definition->getArguments();
328
        $this->assertInstanceOf(Reference::class, $arguments[0]);
329
        $this->assertEquals('cache.system', (string) $arguments[0]);
330
331
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_query_cache'));
332
        $this->assertEquals(DoctrineProvider::class, $definition->getClass());
333
        $arguments = $definition->getArguments();
334
        $this->assertInstanceOf(Reference::class, $arguments[0]);
335
        $this->assertEquals('cache.app', (string) $arguments[0]);
336
337
        $definition = $container->getDefinition((string) $container->getAlias('doctrine.orm.default_result_cache'));
338
        $this->assertEquals(DoctrineProvider::class, $definition->getClass());
339
        $arguments = $definition->getArguments();
340
        $this->assertInstanceOf(Reference::class, $arguments[0]);
341
        $this->assertEquals('cache.app', (string) $arguments[0]);
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);
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...
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
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
401
402
        $this->assertDICConstructorArguments($definition, [
403
            new Reference('doctrine.dbal.default_connection'),
404
            new Reference('doctrine.orm.default_configuration'),
405
        ]);
406
    }
407
408
    public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration()
409
    {
410
        $container = $this->getContainer();
411
        $extension = new DoctrineExtension();
412
413
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
414
            ->addBaseSecondLevelCache()
415
            ->build();
416
417
        $extension->load([$configurationArray], $container);
418
        $this->compileContainer($container);
419
420
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
421
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
422
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
423
424
        $this->assertDICConstructorArguments($definition, [
425
            new Reference('doctrine.dbal.default_connection'),
426
            new Reference('doctrine.orm.default_configuration'),
427
        ]);
428
429
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
430
        $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass());
431
    }
432
433
    public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration()
434
    {
435
        $container = $this->getContainer();
436
        $extension = new DoctrineExtension();
437
438
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
439
            ->addSecondLevelCache([
440
                'region_cache_driver' => ['type' => 'service', 'id' => 'my_cache'],
441
                'regions' => [
442
                    'hour_region' => ['lifetime' => 3600],
443
                ],
444
                'factory' => 'YamlBundle\Cache\MyCacheFactory',
445
            ])
446
            ->build();
447
448
        $extension->load([$configurationArray], $container);
449
        $this->compileContainer($container);
450
451
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
452
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
453
        $this->assertEquals(['%doctrine.orm.entity_manager.class%', 'create'], $definition->getFactory());
454
455
        $this->assertDICConstructorArguments($definition, [
456
            new Reference('doctrine.dbal.default_connection'),
457
            new Reference('doctrine.orm.default_configuration'),
458
        ]);
459
460
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
461
        $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass());
462
    }
463
464 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...
465
    {
466
        $container = $this->getContainer();
467
        $extension = new DoctrineExtension();
468
469
        $config        = BundleConfigurationBuilder::createBuilder()
470
             ->addBaseConnection()
471
             ->build();
472
        $config['orm'] = ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['mappings' => ['YamlBundle' => []]]]];
473
        $extension->load([$config], $container);
474
475
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
476
        $this->assertDICDefinitionMethodCallOnce(
477
            $definition,
478
            'setEntityNamespaces',
479
            [['YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity']]
480
        );
481
    }
482
483 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...
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' => ['alias' => 'yml']]]]];
492
        $extension->load([$config], $container);
493
494
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
495
        $this->assertDICDefinitionMethodCallOnce(
496
            $definition,
497
            'setEntityNamespaces',
498
            [['yml' => 'Fixtures\Bundles\YamlBundle\Entity']]
499
        );
500
    }
501
502
    public function testYamlBundleMappingDetection()
503
    {
504
        $container = $this->getContainer('YamlBundle');
505
        $extension = new DoctrineExtension();
506
507
        $config = BundleConfigurationBuilder::createBuilder()
508
            ->addBaseConnection()
509
            ->addBaseEntityManager()
510
            ->build();
511
        $extension->load([$config], $container);
512
513
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
514
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
515
            new Reference('doctrine.orm.default_yml_metadata_driver'),
516
            'Fixtures\Bundles\YamlBundle\Entity',
517
        ]);
518
    }
519
520 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...
521
    {
522
        $container = $this->getContainer('XmlBundle');
523
        $extension = new DoctrineExtension();
524
525
        $config = BundleConfigurationBuilder::createBuilder()
526
            ->addBaseConnection()
527
            ->addEntityManager([
528
                'default_entity_manager' => 'default',
529
                'entity_managers' => [
530
                    'default' => [
531
                        'mappings' => [
532
                            'XmlBundle' => [],
533
                        ],
534
                    ],
535
                ],
536
            ])
537
            ->build();
538
        $extension->load([$config], $container);
539
540
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
541
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
542
            new Reference('doctrine.orm.default_xml_metadata_driver'),
543
            'Fixtures\Bundles\XmlBundle\Entity',
544
        ]);
545
    }
546
547 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...
548
    {
549
        $container = $this->getContainer('AnnotationsBundle');
550
        $extension = new DoctrineExtension();
551
552
        $config = BundleConfigurationBuilder::createBuilder()
553
            ->addBaseConnection()
554
            ->addEntityManager([
555
                'default_entity_manager' => 'default',
556
                'entity_managers' => [
557
                    'default' => [
558
                        'mappings' => [
559
                            'AnnotationsBundle' => [],
560
                        ],
561
                    ],
562
                ],
563
            ])
564
            ->build();
565
        $extension->load([$config], $container);
566
567
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
568
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', [
569
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
570
            'Fixtures\Bundles\AnnotationsBundle\Entity',
571
        ]);
572
    }
573
574
    public function testOrmMergeConfigs()
575
    {
576
        $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...
577
        $extension = new DoctrineExtension();
578
579
        $config1 = BundleConfigurationBuilder::createBuilder()
580
            ->addBaseConnection()
581
            ->addEntityManager([
582
                'auto_generate_proxy_classes' => true,
583
                'default_entity_manager' => 'default',
584
                'entity_managers' => [
585
                    'default' => [
586
                        'mappings' => [
587
                            'AnnotationsBundle' => [],
588
                        ],
589
                    ],
590
                ],
591
            ])
592
            ->build();
593
        $config2 = BundleConfigurationBuilder::createBuilder()
594
            ->addBaseConnection()
595
            ->addEntityManager([
596
                'auto_generate_proxy_classes' => false,
597
                'default_entity_manager' => 'default',
598
                'entity_managers' => [
599
                    'default' => [
600
                        'mappings' => [
601
                            'XmlBundle' => [],
602
                        ],
603
                    ],
604
                ],
605
            ])
606
            ->build();
607
        $extension->load([$config1, $config2], $container);
608
609
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
610
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', [
611
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
612
            'Fixtures\Bundles\AnnotationsBundle\Entity',
613
        ]);
614
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', [
615
            new Reference('doctrine.orm.default_xml_metadata_driver'),
616
            'Fixtures\Bundles\XmlBundle\Entity',
617
        ]);
618
619
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
620
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses');
621
622
        $calls = $configDef->getMethodCalls();
623
        foreach ($calls as $call) {
624
            if ($call[0] === 'setAutoGenerateProxyClasses') {
625
                $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0]));
626
                break;
627
            }
628
        }
629
    }
630
631
    public function testAnnotationsBundleMappingDetectionWithVendorNamespace()
632
    {
633
        $container = $this->getContainer('AnnotationsBundle', 'Vendor');
634
        $extension = new DoctrineExtension();
635
636
        $config = BundleConfigurationBuilder::createBuilder()
637
            ->addBaseConnection()
638
            ->addEntityManager([
639
                'default_entity_manager' => 'default',
640
                'entity_managers' => [
641
                    'default' => [
642
                        'mappings' => [
643
                            'AnnotationsBundle' => [],
644
                        ],
645
                    ],
646
                ],
647
            ])
648
            ->build();
649
        $extension->load([$config], $container);
650
651
        $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls();
652
        $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]);
653
        $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]);
654
    }
655
656
    public function testMessengerIntegration()
657
    {
658
        if (! interface_exists(MessageBusInterface::class)) {
659
            $this->markTestSkipped('Symfony Messenger component is not installed');
660
        }
661
662
        $container = $this->getContainer();
663
        $extension = new DoctrineExtension();
664
665
        $config = BundleConfigurationBuilder::createBuilder()
666
            ->addBaseConnection()
667
            ->addEntityManager([
668
                'default_entity_manager' => 'default',
669
                'entity_managers' => [
670
                    'default' => [],
671
                ],
672
            ])
673
            ->build();
674
        $extension->load([$config], $container);
675
676
        $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_transaction'));
677
        $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...
678
        $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_clear_entity_manager'));
679
        $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...
680
        $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_ping_connection'));
681
        $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...
682
        $this->assertNotNull($middlewarePrototype = $container->getDefinition('messenger.middleware.doctrine_close_connection'));
683
        $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...
684
    }
685
686
    public function testInvalidCacheConfiguration() : void
687
    {
688
        $container = $this->getContainer();
689
        $extension = new DoctrineExtension();
690
691
        $config = BundleConfigurationBuilder::createBuilder()
692
            ->addBaseConnection()
693
            ->addEntityManager(['metadata_cache_driver' => 'redis'])
694
            ->build();
695
696
        $this->expectException(InvalidArgumentException::class);
697
        $this->expectExceptionMessage('Unknown cache of type "redis" configured for cache "metadata_cache" in entity manager "default"');
698
699
        $extension->load([$config], $container);
700
    }
701
702
    /**
703
     * @param array|string $cacheConfig
704
     *
705
     * @dataProvider cacheConfigurationProvider
706
     */
707
    public function testCacheConfiguration(string $expectedAliasName, string $expectedAliasTarget, string $cacheName, $cacheConfig) : void
708
    {
709
        $container = $this->getContainer();
710
        $extension = new DoctrineExtension();
711
712
        $config = BundleConfigurationBuilder::createBuilder()
713
            ->addBaseConnection()
714
            ->addEntityManager([$cacheName => $cacheConfig])
715
            ->build();
716
717
        $extension->load([$config], $container);
718
719
        $this->assertTrue($container->hasAlias($expectedAliasName));
720
        $alias = $container->getAlias($expectedAliasName);
721
        $this->assertEquals($expectedAliasTarget, (string) $alias);
722
    }
723
724
    public static function cacheConfigurationProvider() : array
725
    {
726
        return [
727
            'metadata_cache_default' => [
728
                'expectedAliasName' => 'doctrine.orm.default_metadata_cache',
729
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.cache.system',
730
                'cacheName' => 'metadata_cache_driver',
731
                'cacheConfig' => ['type' => null],
732
            ],
733
            'query_cache_default' => [
734
                'expectedAliasName' => 'doctrine.orm.default_query_cache',
735
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.cache.app',
736
                'cacheName' => 'query_cache_driver',
737
                'cacheConfig' => ['type' => null],
738
            ],
739
            'result_cache_default' => [
740
                'expectedAliasName' => 'doctrine.orm.default_result_cache',
741
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.cache.app',
742
                'cacheName' => 'result_cache_driver',
743
                'cacheConfig' => ['type' => null],
744
            ],
745
746
            'metadata_cache_pool' => [
747
                'expectedAliasName' => 'doctrine.orm.default_metadata_cache',
748
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.metadata_cache_pool',
749
                'cacheName' => 'metadata_cache_driver',
750
                'cacheConfig' => ['type' => 'pool', 'pool' => 'metadata_cache_pool'],
751
            ],
752
            'query_cache_pool' => [
753
                'expectedAliasName' => 'doctrine.orm.default_query_cache',
754
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.query_cache_pool',
755
                'cacheName' => 'query_cache_driver',
756
                'cacheConfig' => ['type' => 'pool', 'pool' => 'query_cache_pool'],
757
            ],
758
            'result_cache_pool' => [
759
                'expectedAliasName' => 'doctrine.orm.default_result_cache',
760
                'expectedAliasTarget' => 'doctrine.orm.cache.pool.result_cache_pool',
761
                'cacheName' => 'result_cache_driver',
762
                'cacheConfig' => ['type' => 'pool', 'pool' => 'result_cache_pool'],
763
            ],
764
765
            'metadata_cache_service' => [
766
                'expectedAliasName' => 'doctrine.orm.default_metadata_cache',
767
                'expectedAliasTarget' => 'service_target_metadata',
768
                'cacheName' => 'metadata_cache_driver',
769
                'cacheConfig' => ['type' => 'service', 'id' => 'service_target_metadata'],
770
            ],
771
            'query_cache_service' => [
772
                'expectedAliasName' => 'doctrine.orm.default_query_cache',
773
                'expectedAliasTarget' => 'service_target_query',
774
                'cacheName' => 'query_cache_driver',
775
                'cacheConfig' => ['type' => 'service', 'id' => 'service_target_query'],
776
            ],
777
            'result_cache_service' => [
778
                'expectedAliasName' => 'doctrine.orm.default_result_cache',
779
                'expectedAliasTarget' => 'service_target_result',
780
                'cacheName' => 'result_cache_driver',
781
                'cacheConfig' => ['type' => 'service', 'id' => 'service_target_result'],
782
            ],
783
        ];
784
    }
785
786
    public function testShardManager()
787
    {
788
        $container = $this->getContainer();
789
        $extension = new DoctrineExtension();
790
791
        $config = BundleConfigurationBuilder::createBuilder()
792
             ->addConnection([
793
                 'connections' => [
794
                     'foo' => [
795
                         'shards' => [
796
                             'test' => ['id' => 1],
797
                         ],
798
                     ],
799
                     'bar' => [],
800
                 ],
801
             ])
802
            ->build();
803
804
        $extension->load([$config], $container);
805
806
        $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager'));
807
        $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager'));
808
    }
809
810
    private function getContainer($bundles = 'YamlBundle', $vendor = null)
811
    {
812
        $bundles = (array) $bundles;
813
814
        $map = [];
815
        foreach ($bundles as $bundle) {
816
            require_once __DIR__ . '/Fixtures/Bundles/' . ($vendor ? $vendor . '/' : '') . $bundle . '/' . $bundle . '.php';
817
818
            $map[$bundle] = 'Fixtures\\Bundles\\' . ($vendor ? $vendor . '\\' : '') . $bundle . '\\' . $bundle;
819
        }
820
821
        $container = new ContainerBuilder(new ParameterBag([
822
            'kernel.name' => 'app',
823
            'kernel.debug' => false,
824
            'kernel.bundles' => $map,
825
            'kernel.cache_dir' => sys_get_temp_dir(),
826
            'kernel.environment' => 'test',
827
            'kernel.root_dir' => __DIR__ . '/../../', // src dir
828
        ]));
829
830
        // Register dummy cache services so we don't have to load the FrameworkExtension
831
        $container->setDefinition('cache.system', (new Definition(ArrayAdapter::class))->setPublic(true));
832
        $container->setDefinition('cache.app', (new Definition(ArrayAdapter::class))->setPublic(true));
833
        $container->setDefinition('my_pool', (new Definition(ArrayAdapter::class))->setPublic(true));
834
835
        return $container;
836
    }
837
838
    private function assertDICConstructorArguments(Definition $definition, array $args)
839
    {
840
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '" . $definition->getClass() . "' don't match.");
841
    }
842
843 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...
844
    {
845
        $calls = $definition->getMethodCalls();
846
        if (! isset($calls[$pos][0])) {
847
            return;
848
        }
849
850
        $this->assertEquals($methodName, $calls[$pos][0], "Method '" . $methodName . "' is expected to be called at position " . $pos . '.');
851
852
        if ($params === null) {
853
            return;
854
        }
855
856
        $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
857
    }
858
859
    /**
860
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
861
     *
862
     * @param string     $methodName
863
     * @param array|null $params
864
     */
865 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...
866
    {
867
        $calls  = $definition->getMethodCalls();
868
        $called = false;
869
        foreach ($calls as $call) {
870
            if ($call[0] !== $methodName) {
871
                continue;
872
            }
873
874
            if ($called) {
875
                $this->fail("Method '" . $methodName . "' is expected to be called only once, a second call was registered though.");
876
            } else {
877
                $called = true;
878
                if ($params !== null) {
879
                    $this->assertEquals($params, $call[1], "Expected parameters to methods '" . $methodName . "' do not match the actual parameters.");
880
                }
881
            }
882
        }
883
        if ($called) {
884
            return;
885
        }
886
887
        $this->fail("Method '" . $methodName . "' is expected to be called once, definition does not contain a call though.");
888
    }
889
890
    private function compileContainer(ContainerBuilder $container)
891
    {
892
        $container->getCompilerPassConfig()->setOptimizationPasses([new ResolveChildDefinitionsPass()]);
893
        $container->getCompilerPassConfig()->setRemovingPasses([]);
894
        $container->compile();
895
    }
896
}
897
898
class TestWrapperClass extends Connection
899
{
900
}
901