Completed
Push — master ( 4e013f...819c1f )
by Fabien
01:56
created

testPublicServicesAndAliases()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Doctrine Bundle
5
 *
6
 * The code was originally distributed inside the Symfony framework.
7
 *
8
 * (c) Fabien Potencier <[email protected]>
9
 * (c) Doctrine Project, Benjamin Eberlei <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Doctrine\Bundle\DoctrineBundle\Tests\DependencyInjection;
16
17
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\DoctrineExtension;
18
use Doctrine\Bundle\DoctrineBundle\Tests\Builder\BundleConfigurationBuilder;
19
use Doctrine\Common\Persistence\ManagerRegistry;
20
use Doctrine\Common\Persistence\ObjectManager;
21
use Doctrine\Common\Proxy\AbstractProxyFactory;
22
use Doctrine\DBAL\Connection;
23
use Doctrine\DBAL\Driver\Connection as DriverConnection;
24
use Doctrine\ORM\EntityManagerInterface;
25
use Doctrine\ORM\Version;
26
use PHPUnit\Framework\TestCase;
27
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
28
use Symfony\Component\DependencyInjection\ContainerBuilder;
29
use Symfony\Component\DependencyInjection\Definition;
30
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
31
use Symfony\Component\DependencyInjection\Reference;
32
33
class DoctrineExtensionTest extends TestCase
34
{
35
    public function testAutowiringAlias()
36
    {
37
        $container = $this->getContainer();
38
        $extension = new DoctrineExtension();
39
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
40
41
        $extension->load(array($config), $container);
42
43
        $expectedAliases = array(
44
            DriverConnection::class => 'database_connection',
45
            Connection::class => 'database_connection',
46
            ManagerRegistry::class => 'doctrine',
47
            ObjectManager::class => 'doctrine.orm.entity_manager',
48
            EntityManagerInterface::class => 'doctrine.orm.entity_manager',
49
        );
50
51
        foreach ($expectedAliases as $id => $target) {
52
            $this->assertTrue($container->hasAlias($id), sprintf('The container should have a `%s` alias for autowiring support.', $id));
53
54
            $alias = $container->getAlias($id);
55
            $this->assertEquals($target, (string) $alias, sprintf('The autowiring for `%s` should use `%s`.', $id, $target));
56
            $this->assertFalse($alias->isPublic(), sprintf('The autowiring alias for `%s` should be private.', $id, $target));
57
        }
58
    }
59
60
    public function testPublicServicesAndAliases()
61
    {
62
        $container = $this->getContainer();
63
        $extension = new DoctrineExtension();
64
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
65
66
        $extension->load(array($config), $container);
67
68
        $this->assertTrue($container->getDefinition('doctrine')->isPublic());
69
        $this->assertTrue($container->getAlias('doctrine.orm.entity_manager')->isPublic());
70
        $this->assertTrue($container->getAlias('database_connection')->isPublic());
71
    }
72
73
    public function testDbalGenerateDefaultConnectionConfiguration()
74
    {
75
        $container = $this->getContainer();
76
        $extension = new DoctrineExtension();
77
78
        $container->registerExtension($extension);
79
80
        $extension->load(array(array('dbal' => array())), $container);
81
82
        // doctrine.dbal.default_connection
83
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3));
84
        $this->assertEquals('default', $container->getParameter('doctrine.default_connection'));
85
        $this->assertEquals('root', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['user']);
86
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['password']);
87
        $this->assertEquals('localhost', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['host']);
88
        $this->assertNull($container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['port']);
89
        $this->assertEquals('pdo_mysql', $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driver']);
90
        $this->assertEquals(array(), $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0)['driverOptions']);
91
    }
92
93
    public function testDbalOverrideDefaultConnection()
94
    {
95
        $container = $this->getContainer();
96
        $extension = new DoctrineExtension();
97
98
        $container->registerExtension($extension);
99
100
        $extension->load(array(array(), array('dbal' => array('default_connection' => 'foo')), array()), $container);
101
102
        // doctrine.dbal.default_connection
103
        $this->assertEquals('%doctrine.default_connection%', $container->getDefinition('doctrine')->getArgument(3), '->load() overrides existing configuration options');
104
        $this->assertEquals('foo', $container->getParameter('doctrine.default_connection'), '->load() overrides existing configuration options');
105
    }
106
107
    /**
108
     * @expectedException \LogicException
109
     * @expectedExceptionMessage Configuring the ORM layer requires to configure the DBAL layer as well.
110
     */
111
    public function testOrmRequiresDbal()
112
    {
113
        $extension = new DoctrineExtension();
114
115
        $extension->load(array(array('orm' => array('auto_mapping' => true))), $this->getContainer());
116
    }
117
118
    public function getAutomappingConfigurations()
119
    {
120
        return array(
121
            array(
122
                array(
123
                    'em1' => array(
124
                        'mappings' => array(
125
                            'YamlBundle' => null,
126
                        ),
127
                    ),
128
                    'em2' => array(
129
                        'mappings' => array(
130
                            'XmlBundle' => null,
131
                        ),
132
                    ),
133
                ),
134
            ),
135
            array(
136
                array(
137
                    'em1' => array(
138
                        'auto_mapping' => true,
139
                    ),
140
                    'em2' => array(
141
                        'mappings' => array(
142
                            'XmlBundle' => null,
143
                        ),
144
                    ),
145
                ),
146
            ),
147
            array(
148
                array(
149
                    'em1' => array(
150
                        'auto_mapping' => true,
151
                        'mappings' => array(
152
                            'YamlBundle' => null,
153
                        ),
154
                    ),
155
                    'em2' => array(
156
                        'mappings' => array(
157
                            'XmlBundle' => null,
158
                        ),
159
                    ),
160
                ),
161
            ),
162
        );
163
    }
164
165
    /**
166
     * @dataProvider getAutomappingConfigurations
167
     */
168
    public function testAutomapping(array $entityManagers)
169
    {
170
        $extension = new DoctrineExtension();
171
172
        if (!method_exists($extension, 'fixManagersAutoMappings')) {
173
            $this->markTestSkipped('Auto mapping with multiple managers available with Symfony ~2.6');
174
        }
175
176
        $container = $this->getContainer(array(
0 ignored issues
show
Documentation introduced by
array('YamlBundle', 'XmlBundle') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
177
            'YamlBundle',
178
            'XmlBundle',
179
        ));
180
181
        $extension->load(
182
            array(
183
                array(
184
                    'dbal' => array(
185
                        'default_connection' => 'cn1',
186
                        'connections' => array(
187
                            'cn1' => array(),
188
                            'cn2' => array(),
189
                        ),
190
                    ),
191
                    'orm' => array(
192
                        'entity_managers' => $entityManagers,
193
                    ),
194
                ),
195
            ), $container);
196
197
        $configEm1 = $container->getDefinition('doctrine.orm.em1_configuration');
198
        $configEm2 = $container->getDefinition('doctrine.orm.em2_configuration');
199
200
        $this->assertContains(
201
            array(
202
                'setEntityNamespaces',
203
                array(
204
                    array(
205
                        'YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity',
206
                    ),
207
                ),
208
            ),
209
            $configEm1->getMethodCalls()
210
        );
211
212
        $this->assertContains(
213
            array(
214
                'setEntityNamespaces',
215
                array(
216
                    array(
217
                        'XmlBundle' => 'Fixtures\Bundles\XmlBundle\Entity',
218
                    ),
219
                ),
220
            ),
221
            $configEm2->getMethodCalls()
222
        );
223
    }
224
225
    public function testDbalLoad()
226
    {
227
        $container = $this->getContainer();
228
        $extension = new DoctrineExtension();
229
230
        $extension->load(array(
231
            array('dbal' => array('connections' => array('default' => array('password' => 'foo')))),
232
            array(),
233
            array('dbal' => array('default_connection' => 'foo')),
234
            array()), $container);
235
236
        $config = $container->getDefinition('doctrine.dbal.default_connection')->getArgument(0);
237
238
        $this->assertEquals('foo', $config['password']);
239
        $this->assertEquals('root', $config['user']);
240
    }
241
242
    public function testDbalWrapperClass()
243
    {
244
        $container = $this->getContainer();
245
        $extension = new DoctrineExtension();
246
247
        $extension->load(
248
            array(
249
                array('dbal' => array('connections' => array(
250
                    'default' => array('password' => 'foo', 'wrapper_class' => TestWrapperClass::class),
251
                    'second' => array('password' => 'boo'),
252
                ))),
253
                array(),
254
                array('dbal' => array('default_connection' => 'foo')),
255
                array()
256
            ),
257
            $container
258
        );
259
260
        $this->assertEquals(TestWrapperClass::class, $container->getDefinition('doctrine.dbal.default_connection')->getClass());
261
        $this->assertNull($container->getDefinition('doctrine.dbal.second_connection')->getClass());
262
    }
263
264
    public function testDependencyInjectionConfigurationDefaults()
265
    {
266
        $container = $this->getContainer();
267
        $extension = new DoctrineExtension();
268
        $config = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
269
270
        $extension->load(array($config), $container);
271
272
        $this->assertFalse($container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
273
        $this->assertEquals('Doctrine\ORM\Configuration', $container->getParameter('doctrine.orm.configuration.class'));
274
        $this->assertEquals('Doctrine\ORM\EntityManager', $container->getParameter('doctrine.orm.entity_manager.class'));
275
        $this->assertEquals('Proxies', $container->getParameter('doctrine.orm.proxy_namespace'));
276
        $this->assertEquals('Doctrine\Common\Cache\ArrayCache', $container->getParameter('doctrine.orm.cache.array.class'));
277
        $this->assertEquals('Doctrine\Common\Cache\ApcCache', $container->getParameter('doctrine.orm.cache.apc.class'));
278
        $this->assertEquals('Doctrine\Common\Cache\MemcacheCache', $container->getParameter('doctrine.orm.cache.memcache.class'));
279
        $this->assertEquals('localhost', $container->getParameter('doctrine.orm.cache.memcache_host'));
280
        $this->assertEquals('11211', $container->getParameter('doctrine.orm.cache.memcache_port'));
281
        $this->assertEquals('Memcache', $container->getParameter('doctrine.orm.cache.memcache_instance.class'));
282
        $this->assertEquals('Doctrine\Common\Cache\XcacheCache', $container->getParameter('doctrine.orm.cache.xcache.class'));
283
        $this->assertEquals('Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain', $container->getParameter('doctrine.orm.metadata.driver_chain.class'));
284
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\AnnotationDriver', $container->getParameter('doctrine.orm.metadata.annotation.class'));
285
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedXmlDriver', $container->getParameter('doctrine.orm.metadata.xml.class'));
286
        $this->assertEquals('Doctrine\ORM\Mapping\Driver\SimplifiedYamlDriver', $container->getParameter('doctrine.orm.metadata.yml.class'));
287
288
        // second-level cache
289
        $this->assertEquals('Doctrine\ORM\Cache\DefaultCacheFactory', $container->getParameter('doctrine.orm.second_level_cache.default_cache_factory.class'));
290
        $this->assertEquals('Doctrine\ORM\Cache\Region\DefaultRegion', $container->getParameter('doctrine.orm.second_level_cache.default_region.class'));
291
        $this->assertEquals('Doctrine\ORM\Cache\Region\FileLockRegion', $container->getParameter('doctrine.orm.second_level_cache.filelock_region.class'));
292
        $this->assertEquals('Doctrine\ORM\Cache\Logging\CacheLoggerChain', $container->getParameter('doctrine.orm.second_level_cache.logger_chain.class'));
293
        $this->assertEquals('Doctrine\ORM\Cache\Logging\StatisticsCacheLogger', $container->getParameter('doctrine.orm.second_level_cache.logger_statistics.class'));
294
        $this->assertEquals('Doctrine\ORM\Cache\CacheConfiguration', $container->getParameter('doctrine.orm.second_level_cache.cache_configuration.class'));
295
        $this->assertEquals('Doctrine\ORM\Cache\RegionsConfiguration', $container->getParameter('doctrine.orm.second_level_cache.regions_configuration.class'));
296
297
298
        $config = BundleConfigurationBuilder::createBuilder()
299
            ->addBaseConnection()
300
            ->addEntityManager(array(
301
                'proxy_namespace' => 'MyProxies',
302
                'auto_generate_proxy_classes' => true,
303
                'default_entity_manager' => 'default',
304
                'entity_managers' => array(
305
                    'default' => array(
306
                        'mappings' => array('YamlBundle' => array()),
307
                    ),
308
                ),
309
            ))
310
            ->build();
311
312
        $container = $this->getContainer();
313
        $extension->load(array($config), $container);
314
        $this->compileContainer($container);
315
316
        $definition = $container->getDefinition('doctrine.dbal.default_connection');
317
318
        $args = $definition->getArguments();
319
        $this->assertEquals('pdo_mysql', $args[0]['driver']);
320
        $this->assertEquals('localhost', $args[0]['host']);
321
        $this->assertEquals('root', $args[0]['user']);
322
        $this->assertEquals('doctrine.dbal.default_connection.configuration', (string) $args[1]);
323
        $this->assertEquals('doctrine.dbal.default_connection.event_manager', (string) $args[2]);
324
        $this->assertCount(0, $definition->getMethodCalls());
325
326
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
327
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
328 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
329
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
330
        } else {
331
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
332
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
333
        }
334
335
        $this->assertEquals(array('default' => 'doctrine.orm.default_entity_manager'), $container->getParameter('doctrine.entity_managers'), "Set of the existing EntityManagers names is incorrect.");
336
        $this->assertEquals('%doctrine.entity_managers%', $container->getDefinition('doctrine')->getArgument(2), "Set of the existing EntityManagers names is incorrect.");
337
338
        $arguments = $definition->getArguments();
339
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[0]);
340
        $this->assertEquals('doctrine.dbal.default_connection', (string) $arguments[0]);
341
        $this->assertInstanceOf('Symfony\Component\DependencyInjection\Reference', $arguments[1]);
342
        $this->assertEquals('doctrine.orm.default_configuration', (string) $arguments[1]);
343
344
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
345
        $calls = array_values($definition->getMethodCalls());
346
        $this->assertEquals(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'), $calls[0][1][0]);
347
        $this->assertEquals('doctrine.orm.default_metadata_cache', (string) $calls[1][1][0]);
348
        $this->assertEquals('doctrine.orm.default_query_cache', (string) $calls[2][1][0]);
349
        $this->assertEquals('doctrine.orm.default_result_cache', (string) $calls[3][1][0]);
350
351
        if (version_compare(Version::VERSION, "2.3.0-DEV") >= 0) {
352
            $this->assertEquals('doctrine.orm.naming_strategy.default', (string) $calls[10][1][0]);
353
            $this->assertEquals('doctrine.orm.quote_strategy.default', (string) $calls[11][1][0]);
354
        }
355
        if (version_compare(Version::VERSION, "2.4.0-DEV") >= 0) {
356
            $this->assertEquals('doctrine.orm.default_entity_listener_resolver', (string) $calls[12][1][0]);
357
        }
358
359
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_metadata_cache'));
360
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
361
362
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_query_cache'));
363
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
364
365
        $definition = $container->getDefinition($container->getAlias('doctrine.orm.default_result_cache'));
366
        $this->assertEquals('%doctrine_cache.array.class%', $definition->getClass());
367
    }
368
369
    public function testUseSavePointsAddMethodCallToAddSavepointsToTheConnection()
370
    {
371
        $container = $this->getContainer();
372
        $extension = new DoctrineExtension();
373
374
        $extension->load(array(array('dbal' => array('connections' => array(
375
            'default' => array('password' => 'foo', 'use_savepoints' => true)
376
        )))), $container);
377
378
        $calls = $container->getDefinition('doctrine.dbal.default_connection')->getMethodCalls();
379
        $this->assertCount(1, $calls);
380
        $this->assertEquals('setNestTransactionsWithSavepoints', $calls[0][0]);
381
        $this->assertTrue($calls[0][1][0]);
382
    }
383
384
    public function testAutoGenerateProxyClasses()
385
    {
386
        $container = $this->getContainer();
387
        $extension = new DoctrineExtension();
388
389
        $config = BundleConfigurationBuilder::createBuilder()
390
            ->addBaseConnection()
391
            ->addEntityManager(array(
392
                'proxy_namespace' => 'MyProxies',
393
                'auto_generate_proxy_classes' => 'eval',
394
                'default_entity_manager' => 'default',
395
                'entity_managers' => array(
396
                    'default' => array(
397
                        'mappings' => array('YamlBundle' => array()),
398
                    ),
399
                ),
400
            ))
401
            ->build();
402
403
        $extension->load(array($config), $container);
404
405
        $this->assertEquals(AbstractProxyFactory::AUTOGENERATE_EVAL, $container->getParameter('doctrine.orm.auto_generate_proxy_classes'));
406
    }
407
408
    public function testSingleEntityManagerWithDefaultConfiguration()
409
    {
410
        $container = $this->getContainer();
411
        $extension = new DoctrineExtension();
412
413
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()->build();
414
415
        $extension->load(array($configurationArray), $container);
416
        $this->compileContainer($container);
417
418
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
419
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
420 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
421
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
422
        } else {
423
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
424
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
425
        }
426
427
        $this->assertDICConstructorArguments($definition, array(
428
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
429
        ));
430
    }
431
432
    public function testSingleEntityManagerWithDefaultSecondLevelCacheConfiguration()
433
    {
434
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
435
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
436
        }
437
        $container = $this->getContainer();
438
        $extension = new DoctrineExtension();
439
440
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
441
            ->addBaseSecondLevelCache()
442
            ->build();
443
444
        $extension->load(array($configurationArray), $container);
445
        $this->compileContainer($container);
446
447
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
448
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
449
        if (method_exists($definition, 'getFactory')) {
450
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
451
        } else {
452
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
453
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
454
        }
455
456
        $this->assertDICConstructorArguments($definition, array(
457
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
458
        ));
459
460
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
461
        $this->assertEquals('%doctrine.orm.second_level_cache.default_cache_factory.class%', $slcDefinition->getClass());
462
    }
463
464
    public function testSingleEntityManagerWithCustomSecondLevelCacheConfiguration()
465
    {
466
        if (version_compare(Version::VERSION, "2.5.0-DEV") < 0) {
467
            $this->markTestSkipped(sprintf('Second Level cache not supported by this version of the ORM : %s', Version::VERSION));
468
        }
469
        $container = $this->getContainer();
470
        $extension = new DoctrineExtension();
471
472
        $configurationArray = BundleConfigurationBuilder::createBuilderWithBaseValues()
473
            ->addSecondLevelCache([
474
                'region_cache_driver' => [
475
                    'type' => 'memcache'],
476
                'regions' => [
477
                    'hour_region' => [
478
                        'lifetime' => 3600
479
                    ]
480
                ],
481
                'factory' => 'YamlBundle\Cache\MyCacheFactory',
482
            ])
483
            ->build();
484
485
        $extension->load(array($configurationArray), $container);
486
        $this->compileContainer($container);
487
488
        $definition = $container->getDefinition('doctrine.orm.default_entity_manager');
489
        $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getClass());
490 View Code Duplication
        if (method_exists($definition, 'getFactory')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
491
            $this->assertEquals(array('%doctrine.orm.entity_manager.class%', 'create'), $definition->getFactory());
492
        } else {
493
            $this->assertEquals('%doctrine.orm.entity_manager.class%', $definition->getFactoryClass());
0 ignored issues
show
Bug introduced by
The method getFactoryClass() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
494
            $this->assertEquals('create', $definition->getFactoryMethod());
0 ignored issues
show
Bug introduced by
The method getFactoryMethod() does not exist on Symfony\Component\DependencyInjection\Definition. Did you maybe mean getFactory()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
495
        }
496
497
        $this->assertDICConstructorArguments($definition, array(
498
            new Reference('doctrine.dbal.default_connection'), new Reference('doctrine.orm.default_configuration'),
499
        ));
500
501
        $slcDefinition = $container->getDefinition('doctrine.orm.default_second_level_cache.default_cache_factory');
502
        $this->assertEquals('YamlBundle\Cache\MyCacheFactory', $slcDefinition->getClass());
503
    }
504
505 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...
506
    {
507
        $container = $this->getContainer();
508
        $extension = new DoctrineExtension();
509
510
        $config = BundleConfigurationBuilder::createBuilder()
511
             ->addBaseConnection()
512
             ->build();
513
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array()))));
514
        $extension->load(array($config), $container);
515
516
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
517
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
518
            array(array('YamlBundle' => 'Fixtures\Bundles\YamlBundle\Entity'))
519
        );
520
    }
521
522 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...
523
    {
524
        $container = $this->getContainer();
525
        $extension = new DoctrineExtension();
526
527
        $config = BundleConfigurationBuilder::createBuilder()
528
             ->addBaseConnection()
529
             ->build();
530
        $config['orm'] = array('default_entity_manager' => 'default', 'entity_managers' => array('default' => array('mappings' => array('YamlBundle' => array('alias' => 'yml')))));
531
        $extension->load(array($config), $container);
532
533
        $definition = $container->getDefinition('doctrine.orm.default_configuration');
534
        $this->assertDICDefinitionMethodCallOnce($definition, 'setEntityNamespaces',
535
            array(array('yml' => 'Fixtures\Bundles\YamlBundle\Entity'))
536
        );
537
    }
538
539
    public function testYamlBundleMappingDetection()
540
    {
541
        $container = $this->getContainer('YamlBundle');
542
        $extension = new DoctrineExtension();
543
544
        $config = BundleConfigurationBuilder::createBuilder()
545
            ->addBaseConnection()
546
            ->addBaseEntityManager()
547
            ->build();
548
        $extension->load(array($config), $container);
549
550
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
551
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
552
            new Reference('doctrine.orm.default_yml_metadata_driver'),
553
            'Fixtures\Bundles\YamlBundle\Entity',
554
        ));
555
    }
556
557 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...
558
    {
559
        $container = $this->getContainer('XmlBundle');
560
        $extension = new DoctrineExtension();
561
562
        $config = BundleConfigurationBuilder::createBuilder()
563
            ->addBaseConnection()
564
            ->addEntityManager(array(
565
                'default_entity_manager' => 'default',
566
                'entity_managers' => array(
567
                    'default' => array(
568
                        'mappings' => array(
569
                            'XmlBundle' => array()
570
                        )
571
                    )
572
                )
573
            ))
574
            ->build();
575
        $extension->load(array($config), $container);
576
577
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
578
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
579
            new Reference('doctrine.orm.default_xml_metadata_driver'),
580
            'Fixtures\Bundles\XmlBundle\Entity',
581
        ));
582
    }
583
584 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...
585
    {
586
        $container = $this->getContainer('AnnotationsBundle');
587
        $extension = new DoctrineExtension();
588
589
        $config = BundleConfigurationBuilder::createBuilder()
590
            ->addBaseConnection()
591
            ->addEntityManager(array(
592
                'default_entity_manager' => 'default',
593
                'entity_managers' => array(
594
                    'default' => array(
595
                        'mappings' => array(
596
                            'AnnotationsBundle' => array()
597
                        )
598
                    )
599
                )
600
            ))
601
            ->build();
602
        $extension->load(array($config), $container);
603
604
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
605
        $this->assertDICDefinitionMethodCallOnce($definition, 'addDriver', array(
606
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
607
            'Fixtures\Bundles\AnnotationsBundle\Entity',
608
        ));
609
    }
610
611
    public function testOrmMergeConfigs()
612
    {
613
        $container = $this->getContainer(array('XmlBundle', 'AnnotationsBundle'));
0 ignored issues
show
Documentation introduced by
array('XmlBundle', 'AnnotationsBundle') is of type array<integer,string,{"0":"string","1":"string"}>, but the function expects a string.

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

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

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

function acceptsInteger($int) { }

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

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
614
        $extension = new DoctrineExtension();
615
616
        $config1 = BundleConfigurationBuilder::createBuilder()
617
            ->addBaseConnection()
618
            ->addEntityManager(array(
619
                'auto_generate_proxy_classes' => true,
620
                'default_entity_manager' => 'default',
621
                'entity_managers' => array(
622
                    'default' => array(
623
                        'mappings' => array(
624
                            'AnnotationsBundle' => array()
625
                        )
626
                    ),
627
                ),
628
            ))
629
            ->build();
630
        $config2 = BundleConfigurationBuilder::createBuilder()
631
            ->addBaseConnection()
632
            ->addEntityManager(array(
633
                'auto_generate_proxy_classes' => false,
634
                'default_entity_manager' => 'default',
635
                'entity_managers' => array(
636
                    'default' => array(
637
                        'mappings' => array(
638
                            'XmlBundle' => array()
639
                        )
640
                    ),
641
                ),
642
            ))
643
            ->build();
644
        $extension->load(array($config1, $config2), $container);
645
646
        $definition = $container->getDefinition('doctrine.orm.default_metadata_driver');
647
        $this->assertDICDefinitionMethodCallAt(0, $definition, 'addDriver', array(
648
            new Reference('doctrine.orm.default_annotation_metadata_driver'),
649
            'Fixtures\Bundles\AnnotationsBundle\Entity',
650
        ));
651
        $this->assertDICDefinitionMethodCallAt(1, $definition, 'addDriver', array(
652
            new Reference('doctrine.orm.default_xml_metadata_driver'),
653
            'Fixtures\Bundles\XmlBundle\Entity',
654
        ));
655
656
        $configDef = $container->getDefinition('doctrine.orm.default_configuration');
657
        $this->assertDICDefinitionMethodCallOnce($configDef, 'setAutoGenerateProxyClasses');
658
659
        $calls = $configDef->getMethodCalls();
660
        foreach ($calls as $call) {
661
            if ($call[0] === 'setAutoGenerateProxyClasses') {
662
                $this->assertFalse($container->getParameterBag()->resolveValue($call[1][0]));
663
                break;
664
            }
665
        }
666
    }
667
668
    public function testAnnotationsBundleMappingDetectionWithVendorNamespace()
669
    {
670
        $container = $this->getContainer('AnnotationsBundle', 'Vendor');
671
        $extension = new DoctrineExtension();
672
673
        $config = BundleConfigurationBuilder::createBuilder()
674
            ->addBaseConnection()
675
            ->addEntityManager(array(
676
                'default_entity_manager' => 'default',
677
                'entity_managers' => array(
678
                    'default' => array(
679
                        'mappings' => array(
680
                            'AnnotationsBundle' => array()
681
                        )
682
                    )
683
                )
684
            ))
685
            ->build();
686
        $extension->load(array($config), $container);
687
688
        $calls = $container->getDefinition('doctrine.orm.default_metadata_driver')->getMethodCalls();
689
        $this->assertEquals('doctrine.orm.default_annotation_metadata_driver', (string) $calls[0][1][0]);
690
        $this->assertEquals('Fixtures\Bundles\Vendor\AnnotationsBundle\Entity', $calls[0][1][1]);
691
    }
692
693
    public function testCacheConfiguration()
694
    {
695
        $container = $this->getContainer();
696
        $extension = new DoctrineExtension();
697
698
        $config = BundleConfigurationBuilder::createBuilder()
699
             ->addBaseConnection()
700
             ->addEntityManager(array(
701
                 'metadata_cache_driver' => array(
702
                     'cache_provider' => 'metadata_cache',
703
                 ),
704
                 'query_cache_driver' => array(
705
                     'cache_provider' => 'query_cache',
706
                 ),
707
                 'result_cache_driver' => array(
708
                     'cache_provider' => 'result_cache',
709
                 ),
710
             ))
711
            ->build();
712
713
        $extension->load(array($config), $container);
714
715
        $this->assertTrue($container->hasAlias('doctrine.orm.default_metadata_cache'));
716
        $alias = $container->getAlias('doctrine.orm.default_metadata_cache');
717
        $this->assertEquals('doctrine_cache.providers.metadata_cache', (string) $alias);
718
719
        $this->assertTrue($container->hasAlias('doctrine.orm.default_query_cache'));
720
        $alias = $container->getAlias('doctrine.orm.default_query_cache');
721
        $this->assertEquals('doctrine_cache.providers.query_cache', (string) $alias);
722
723
        $this->assertTrue($container->hasAlias('doctrine.orm.default_result_cache'));
724
        $alias = $container->getAlias('doctrine.orm.default_result_cache');
725
        $this->assertEquals('doctrine_cache.providers.result_cache', (string) $alias);
726
    }
727
728
    public function testShardManager()
729
    {
730
        $container = $this->getContainer();
731
        $extension = new DoctrineExtension();
732
733
        $config = BundleConfigurationBuilder::createBuilder()
734
             ->addConnection(array(
735
                 'connections' => array(
736
                     'foo' => array(
737
                         'shards' => array(
738
                             'test' => array('id' => 1)
739
                         ),
740
                     ),
741
                     'bar' => array(),
742
                 ),
743
             ))
744
            ->build();
745
746
        $extension->load(array($config), $container);
747
748
        $this->assertTrue($container->hasDefinition('doctrine.dbal.foo_shard_manager'));
749
        $this->assertFalse($container->hasDefinition('doctrine.dbal.bar_shard_manager'));
750
    }
751
752
    private function getContainer($bundles = 'YamlBundle', $vendor = null)
753
    {
754
        $bundles = (array) $bundles;
755
756
        $map = array();
757
        foreach ($bundles as $bundle) {
758
            require_once __DIR__.'/Fixtures/Bundles/'.($vendor ? $vendor.'/' : '').$bundle.'/'.$bundle.'.php';
759
760
            $map[$bundle] = 'Fixtures\\Bundles\\'.($vendor ? $vendor.'\\' : '').$bundle.'\\'.$bundle;
761
        }
762
763
        return new ContainerBuilder(new ParameterBag(array(
764
            'kernel.name' => 'app',
765
            'kernel.debug' => false,
766
            'kernel.bundles' => $map,
767
            'kernel.cache_dir' => sys_get_temp_dir(),
768
            'kernel.environment' => 'test',
769
            'kernel.root_dir' => __DIR__.'/../../', // src dir
770
        )));
771
    }
772
773
    private function assertDICConstructorArguments(Definition $definition, array $args)
774
    {
775
        $this->assertEquals($args, $definition->getArguments(), "Expected and actual DIC Service constructor arguments of definition '".$definition->getClass()."' don't match.");
776
    }
777
778 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...
779
    {
780
        $calls = $definition->getMethodCalls();
781
        if (isset($calls[$pos][0])) {
782
            $this->assertEquals($methodName, $calls[$pos][0], "Method '".$methodName."' is expected to be called at position $pos.");
783
784
            if ($params !== null) {
785
                $this->assertEquals($params, $calls[$pos][1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
786
            }
787
        }
788
    }
789
790
    /**
791
     * Assertion for the DI Container, check if the given definition contains a method call with the given parameters.
792
     *
793
     * @param Definition $definition
794
     * @param string     $methodName
795
     * @param array|null $params
796
     */
797 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...
798
    {
799
        $calls = $definition->getMethodCalls();
800
        $called = false;
801
        foreach ($calls as $call) {
802
            if ($call[0] === $methodName) {
803
                if ($called) {
804
                    $this->fail("Method '".$methodName."' is expected to be called only once, a second call was registered though.");
805
                } else {
806
                    $called = true;
807
                    if ($params !== null) {
808
                        $this->assertEquals($params, $call[1], "Expected parameters to methods '".$methodName."' do not match the actual parameters.");
809
                    }
810
                }
811
            }
812
        }
813
        if (!$called) {
814
            $this->fail("Method '".$methodName."' is expected to be called once, definition does not contain a call though.");
815
        }
816
    }
817
818
    private function compileContainer(ContainerBuilder $container)
819
    {
820
        $container->getCompilerPassConfig()->setOptimizationPasses(array(new ResolveDefinitionTemplatesPass()));
821
        $container->getCompilerPassConfig()->setRemovingPasses(array());
822
        $container->compile();
823
    }
824
825
}
826
827
class TestWrapperClass extends Connection {}
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
828