Completed
Pull Request — master (#601)
by Mike
02:25
created

DoctrineExtensionTest::getConnectionConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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