Completed
Pull Request — master (#939)
by Kévin
01:48
created

DoctrineExtension::loadValidatorLoader()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
3
namespace Doctrine\Bundle\DoctrineBundle\DependencyInjection;
4
5
use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\ServiceRepositoryCompilerPass;
6
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface;
7
use Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\CacheProviderLoader;
8
use Doctrine\Bundle\DoctrineCacheBundle\DependencyInjection\SymfonyBridgeAdapter;
9
use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory;
10
use Doctrine\ORM\Version;
11
use LogicException;
12
use Symfony\Bridge\Doctrine\DependencyInjection\AbstractDoctrineExtension;
13
use Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware;
14
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
15
use Symfony\Bridge\Doctrine\Validator\DoctrineLoader;
16
use Symfony\Component\Config\FileLocator;
17
use Symfony\Component\DependencyInjection\Alias;
18
use Symfony\Component\DependencyInjection\ChildDefinition;
19
use Symfony\Component\DependencyInjection\ContainerBuilder;
20
use Symfony\Component\DependencyInjection\Definition;
21
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
22
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
23
use Symfony\Component\DependencyInjection\Reference;
24
use Symfony\Component\Messenger\MessageBusInterface;
25
use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
26
27
/**
28
 * DoctrineExtension is an extension for the Doctrine DBAL and ORM library.
29
 */
30
class DoctrineExtension extends AbstractDoctrineExtension
31
{
32
    /** @var string */
33
    private $defaultConnection;
34
35
    /** @var SymfonyBridgeAdapter */
36
    private $adapter;
37
38
    public function __construct(SymfonyBridgeAdapter $adapter = null)
39
    {
40
        $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm');
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46
    public function load(array $configs, ContainerBuilder $container)
47
    {
48
        $configuration = $this->getConfiguration($configs, $container);
49
        $config        = $this->processConfiguration($configuration, $configs);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 48 can be null; however, Symfony\Component\Depend...:processConfiguration() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
50
51
        $this->adapter->loadServicesConfiguration($container);
52
53
        if (! empty($config['dbal'])) {
54
            $this->dbalLoad($config['dbal'], $container);
55
        }
56
57
        if (empty($config['orm'])) {
58
            return;
59
        }
60
61
        if (empty($config['dbal'])) {
62
            throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.');
63
        }
64
65
        if (! class_exists(Version::class)) {
66
            throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.');
67
        }
68
69
        $this->ormLoad($config['orm'], $container);
70
    }
71
72
    /**
73
     * Loads the DBAL configuration.
74
     *
75
     * Usage example:
76
     *
77
     *      <doctrine:dbal id="myconn" dbname="sfweb" user="root" />
78
     *
79
     * @param array            $config    An array of configuration settings
80
     * @param ContainerBuilder $container A ContainerBuilder instance
81
     */
82
    protected function dbalLoad(array $config, ContainerBuilder $container)
83
    {
84
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
85
        $loader->load('dbal.xml');
86
87
        if (empty($config['default_connection'])) {
88
            $keys                         = array_keys($config['connections']);
89
            $config['default_connection'] = reset($keys);
90
        }
91
92
        $this->defaultConnection = $config['default_connection'];
93
94
        $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection));
95
        $container->getAlias('database_connection')->setPublic(true);
96
        $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false));
97
98
        $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']);
99
100
        $connections = [];
101
102
        foreach (array_keys($config['connections']) as $name) {
103
            $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name);
104
        }
105
106
        $container->setParameter('doctrine.connections', $connections);
107
        $container->setParameter('doctrine.default_connection', $this->defaultConnection);
108
109
        foreach ($config['connections'] as $name => $connection) {
110
            $this->loadDbalConnection($name, $connection, $container);
111
        }
112
    }
113
114
    /**
115
     * Loads a configured DBAL connection.
116
     *
117
     * @param string           $name       The name of the connection
118
     * @param array            $connection A dbal connection configuration.
119
     * @param ContainerBuilder $container  A ContainerBuilder instance
120
     */
121
    protected function loadDbalConnection($name, array $connection, ContainerBuilder $container)
122
    {
123
        $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration'));
124
        $logger        = null;
125
        if ($connection['logging']) {
126
            $logger = new Reference('doctrine.dbal.logger');
127
        }
128
        unset($connection['logging']);
129
        if ($connection['profiling']) {
130
            $profilingLoggerId = 'doctrine.dbal.logger.profiling.' . $name;
131
            $container->setDefinition($profilingLoggerId, new ChildDefinition('doctrine.dbal.logger.profiling'));
132
            $profilingLogger = new Reference($profilingLoggerId);
133
            $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]);
134
135
            if ($logger !== null) {
136
                $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain');
137
                $chainLogger->addMethodCall('addLogger', [$profilingLogger]);
138
139
                $loggerId = 'doctrine.dbal.logger.chain.' . $name;
140
                $container->setDefinition($loggerId, $chainLogger);
141
                $logger = new Reference($loggerId);
142
            } else {
143
                $logger = $profilingLogger;
144
            }
145
        }
146
        unset($connection['profiling']);
147
148
        if (isset($connection['auto_commit'])) {
149
            $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]);
150
        }
151
152
        unset($connection['auto_commit']);
153
154
        if (isset($connection['schema_filter']) && $connection['schema_filter']) {
155
            $configuration->addMethodCall('setFilterSchemaAssetsExpression', [$connection['schema_filter']]);
156
        }
157
158
        unset($connection['schema_filter']);
159
160
        if ($logger) {
161
            $configuration->addMethodCall('setSQLLogger', [$logger]);
162
        }
163
164
        // event manager
165
        $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager'));
166
167
        // connection
168
        $options = $this->getConnectionOptions($connection);
169
170
        $def = $container
171
            ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection'))
172
            ->setPublic(true)
173
            ->setArguments([
174
                $options,
175
                new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)),
176
                new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)),
177
                $connection['mapping_types'],
178
            ]);
179
180
        // Set class in case "wrapper_class" option was used to assist IDEs
181
        if (isset($options['wrapperClass'])) {
182
            $def->setClass($options['wrapperClass']);
183
        }
184
185
        if (! empty($connection['use_savepoints'])) {
186
            $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]);
187
        }
188
189
        // Create a shard_manager for this connection
190
        if (! isset($options['shards'])) {
191
            return;
192
        }
193
194
        $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]);
195
        $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition);
196
    }
197
198
    protected function getConnectionOptions($connection)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
199
    {
200
        $options = $connection;
201
202
        if (isset($options['platform_service'])) {
203
            $options['platform'] = new Reference($options['platform_service']);
204
            unset($options['platform_service']);
205
        }
206
        unset($options['mapping_types']);
207
208
        if (isset($options['shard_choser_service'])) {
209
            $options['shard_choser'] = new Reference($options['shard_choser_service']);
210
            unset($options['shard_choser_service']);
211
        }
212
213
        foreach ([
214
            'options' => 'driverOptions',
215
            'driver_class' => 'driverClass',
216
            'wrapper_class' => 'wrapperClass',
217
            'keep_slave' => 'keepSlave',
218
            'shard_choser' => 'shardChoser',
219
            'shard_manager_class' => 'shardManagerClass',
220
            'server_version' => 'serverVersion',
221
            'default_table_options' => 'defaultTableOptions',
222
        ] as $old => $new) {
223
            if (! isset($options[$old])) {
224
                continue;
225
            }
226
227
            $options[$new] = $options[$old];
228
            unset($options[$old]);
229
        }
230
231
        if (! empty($options['slaves']) && ! empty($options['shards'])) {
232
            throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together');
233
        }
234
235
        if (! empty($options['slaves'])) {
236
            $nonRewrittenKeys = [
237
                'driver' => true,
238
                'driverOptions' => true,
239
                'driverClass' => true,
240
                'wrapperClass' => true,
241
                'keepSlave' => true,
242
                'shardChoser' => true,
243
                'platform' => true,
244
                'slaves' => true,
245
                'master' => true,
246
                'shards' => true,
247
                'serverVersion' => true,
248
                // included by safety but should have been unset already
249
                'logging' => true,
250
                'profiling' => true,
251
                'mapping_types' => true,
252
                'platform_service' => true,
253
            ];
254 View Code Duplication
            foreach ($options as $key => $value) {
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...
255
                if (isset($nonRewrittenKeys[$key])) {
256
                    continue;
257
                }
258
                $options['master'][$key] = $value;
259
                unset($options[$key]);
260
            }
261
            if (empty($options['wrapperClass'])) {
262
                // Change the wrapper class only if the user does not already forced using a custom one.
263
                $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection';
264
            }
265
        } else {
266
            unset($options['slaves']);
267
        }
268
269
        if (! empty($options['shards'])) {
270
            $nonRewrittenKeys = [
271
                'driver' => true,
272
                'driverOptions' => true,
273
                'driverClass' => true,
274
                'wrapperClass' => true,
275
                'keepSlave' => true,
276
                'shardChoser' => true,
277
                'platform' => true,
278
                'slaves' => true,
279
                'global' => true,
280
                'shards' => true,
281
                'serverVersion' => true,
282
                // included by safety but should have been unset already
283
                'logging' => true,
284
                'profiling' => true,
285
                'mapping_types' => true,
286
                'platform_service' => true,
287
            ];
288 View Code Duplication
            foreach ($options as $key => $value) {
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...
289
                if (isset($nonRewrittenKeys[$key])) {
290
                    continue;
291
                }
292
                $options['global'][$key] = $value;
293
                unset($options[$key]);
294
            }
295
            if (empty($options['wrapperClass'])) {
296
                // Change the wrapper class only if the user does not already forced using a custom one.
297
                $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection';
298
            }
299
            if (empty($options['shardManagerClass'])) {
300
                // Change the shard manager class only if the user does not already forced using a custom one.
301
                $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager';
302
            }
303
        } else {
304
            unset($options['shards']);
305
        }
306
307
        return $options;
308
    }
309
310
    /**
311
     * Loads the Doctrine ORM configuration.
312
     *
313
     * Usage example:
314
     *
315
     *     <doctrine:orm id="mydm" connection="myconn" />
316
     *
317
     * @param array            $config    An array of configuration settings
318
     * @param ContainerBuilder $container A ContainerBuilder instance
319
     */
320
    protected function ormLoad(array $config, ContainerBuilder $container)
321
    {
322
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
323
        $loader->load('orm.xml');
324
325
        $entityManagers = [];
326
        foreach (array_keys($config['entity_managers']) as $name) {
327
            $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name);
328
        }
329
        $container->setParameter('doctrine.entity_managers', $entityManagers);
330
331
        if (empty($config['default_entity_manager'])) {
332
            $tmp                              = array_keys($entityManagers);
333
            $config['default_entity_manager'] = reset($tmp);
334
        }
335
        $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']);
336
337
        $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace'];
338
        foreach ($options as $key) {
339
            $container->setParameter('doctrine.orm.' . $key, $config[$key]);
340
        }
341
342
        $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager']));
343
        $container->getAlias('doctrine.orm.entity_manager')->setPublic(true);
344
345
        $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles'));
346
347
        foreach ($config['entity_managers'] as $name => $entityManager) {
348
            $entityManager['name'] = $name;
349
            $this->loadOrmEntityManager($entityManager, $container);
350
351
            $this->loadPropertyInfoExtractor($name, $container);
352
            $this->loadValidatorLoader($name, $container);
353
        }
354
355
        if ($config['resolve_target_entities']) {
356
            $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
357
            foreach ($config['resolve_target_entities'] as $name => $implementation) {
358
                $def->addMethodCall('addResolveTargetEntity', [
359
                    $name,
360
                    $implementation,
361
                    [],
362
                ]);
363
            }
364
365
            $def->addTag('doctrine.event_subscriber');
366
        }
367
368
        $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class)
369
            ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
370
371
        // If the Messenger component is installed and the doctrine transaction middleware is available, wire it:
372
        if (! interface_exists(MessageBusInterface::class) || ! class_exists(DoctrineTransactionMiddleware::class)) {
373
            return;
374
        }
375
376
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
377
        $loader->load('messenger.xml');
378
    }
379
380
    /**
381
     * Loads a configured ORM entity manager.
382
     *
383
     * @param array            $entityManager A configured ORM entity manager.
384
     * @param ContainerBuilder $container     A ContainerBuilder instance
385
     */
386
    protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container)
387
    {
388
        $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));
389
390
        $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container);
391
        $this->loadOrmCacheDrivers($entityManager, $container);
392
393
        if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
394
            $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']);
395
        } else {
396
            $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
397
            $definition->addArgument(new Reference('service_container'));
398
            $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition);
399
        }
400
401
        $methods = [
402
            'setMetadataCacheImpl' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])),
403
            'setQueryCacheImpl' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])),
404
            'setResultCacheImpl' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])),
405
            'setMetadataDriverImpl' => new Reference('doctrine.orm.' . $entityManager['name'] . '_metadata_driver'),
406
            'setProxyDir' => '%doctrine.orm.proxy_dir%',
407
            'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
408
            'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
409
            'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
410
            'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
411
            'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
412
            'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
413
            'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])),
414
        ];
415
416
        $listenerId        = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']);
417
        $listenerDef       = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
418
        $listenerTagParams = ['event' => 'loadClassMetadata'];
419
        if (isset($entityManager['connection'])) {
420
            $listenerTagParams['connection'] = $entityManager['connection'];
421
        }
422
        $listenerDef->addTag('doctrine.event_listener', $listenerTagParams);
423
424
        if (isset($entityManager['second_level_cache'])) {
425
            $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container);
426
        }
427
428
        if ($entityManager['repository_factory']) {
429
            $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
430
        }
431
432
        foreach ($methods as $method => $arg) {
433
            $ormConfigDef->addMethodCall($method, [$arg]);
434
        }
435
436
        foreach ($entityManager['hydrators'] as $name => $class) {
437
            $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]);
438
        }
439
440
        if (! empty($entityManager['dql'])) {
441
            foreach ($entityManager['dql']['string_functions'] as $name => $function) {
442
                $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]);
443
            }
444
            foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
445
                $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]);
446
            }
447
            foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
448
                $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]);
449
            }
450
        }
451
452
        $enabledFilters    = [];
453
        $filtersParameters = [];
454
        foreach ($entityManager['filters'] as $name => $filter) {
455
            $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]);
456
            if ($filter['enabled']) {
457
                $enabledFilters[] = $name;
458
            }
459
            if (! $filter['parameters']) {
460
                continue;
461
            }
462
463
            $filtersParameters[$name] = $filter['parameters'];
464
        }
465
466
        $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']);
467
        $container
468
            ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
469
            ->replaceArgument(0, $enabledFilters)
470
            ->replaceArgument(1, $filtersParameters);
471
472
        if (! isset($entityManager['connection'])) {
473
            $entityManager['connection'] = $this->defaultConnection;
474
        }
475
476
        $container
477
            ->setDefinition(sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']), new ChildDefinition('doctrine.orm.entity_manager.abstract'))
478
            ->setPublic(true)
479
            ->setArguments([
480
                new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])),
481
                new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])),
482
            ])
483
            ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);
484
485
        $container->setAlias(
486
            sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']),
487
            new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false)
488
        );
489
490
        if (! isset($entityManager['entity_listeners'])) {
491
            return;
492
        }
493
494
        if (! isset($listenerDef)) {
495
            throw new InvalidArgumentException('Entity listeners configuration requires doctrine-orm 2.5.0 or newer');
496
        }
497
498
        $entities = $entityManager['entity_listeners']['entities'];
499
500
        foreach ($entities as $entityListenerClass => $entity) {
501
            foreach ($entity['listeners'] as $listenerClass => $listener) {
502
                foreach ($listener['events'] as $listenerEvent) {
503
                    $listenerEventName = $listenerEvent['type'];
504
                    $listenerMethod    = $listenerEvent['method'];
505
506
                    $listenerDef->addMethodCall('addEntityListener', [
507
                        $entityListenerClass,
508
                        $listenerClass,
509
                        $listenerEventName,
510
                        $listenerMethod,
511
                    ]);
512
                }
513
            }
514
        }
515
    }
516
517
    /**
518
     * Loads an ORM entity managers bundle mapping information.
519
     *
520
     * There are two distinct configuration possibilities for mapping information:
521
     *
522
     * 1. Specify a bundle and optionally details where the entity and mapping information reside.
523
     * 2. Specify an arbitrary mapping location.
524
     *
525
     * @param array            $entityManager A configured ORM entity manager
526
     * @param Definition       $ormConfigDef  A Definition instance
527
     * @param ContainerBuilder $container     A ContainerBuilder instance
528
     *
529
     * @example
530
     *
531
     *  doctrine.orm:
532
     *     mappings:
533
     *         MyBundle1: ~
534
     *         MyBundle2: yml
535
     *         MyBundle3: { type: annotation, dir: Entities/ }
536
     *         MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
537
     *         MyBundle5:
538
     *             type: yml
539
     *             dir: bundle-mappings/
540
     *             alias: BundleAlias
541
     *         arbitrary_key:
542
     *             type: xml
543
     *             dir: %kernel.root_dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities
544
     *             prefix: DoctrineExtensions\Entities\
545
     *             alias: DExt
546
     *
547
     * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
548
     * in the mappings key everything except alias is a required argument.
549
     */
550
    protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
551
    {
552
        // reset state of drivers and alias map. They are only used by this methods and children.
553
        $this->drivers  = [];
554
        $this->aliasMap = [];
555
556
        $this->loadMappingInformation($entityManager, $container);
557
        $this->registerMappingDrivers($entityManager, $container);
558
559
        $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]);
560
    }
561
562
    /**
563
     * Loads an ORM second level cache bundle mapping information.
564
     *
565
     * @param array            $entityManager A configured ORM entity manager
566
     * @param Definition       $ormConfigDef  A Definition instance
567
     * @param ContainerBuilder $container     A ContainerBuilder instance
568
     *
569
     * @example
570
     *  entity_managers:
571
     *      default:
572
     *          second_level_cache:
573
     *              region_cache_driver: apc
574
     *              log_enabled: true
575
     *              regions:
576
     *                  my_service_region:
577
     *                      type: service
578
     *                      service : "my_service_region"
579
     *
580
     *                  my_query_region:
581
     *                      lifetime: 300
582
     *                      cache_driver: array
583
     *                      type: filelock
584
     *
585
     *                  my_entity_region:
586
     *                      lifetime: 600
587
     *                      cache_driver:
588
     *                          type: apc
589
     */
590
    protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
591
    {
592
        $driverId = null;
593
        $enabled  = $entityManager['second_level_cache']['enabled'];
594
595
        if (isset($entityManager['second_level_cache']['region_cache_driver'])) {
596
            $driverName = 'second_level_cache.region_cache_driver';
597
            $driverMap  = $entityManager['second_level_cache']['region_cache_driver'];
598
            $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
599
        }
600
601
        $configId   = sprintf('doctrine.orm.%s_second_level_cache.cache_configuration', $entityManager['name']);
602
        $regionsId  = sprintf('doctrine.orm.%s_second_level_cache.regions_configuration', $entityManager['name']);
603
        $driverId   = $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver', $entityManager['name']);
604
        $configDef  = $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%'));
605
        $regionsDef = $container->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%'));
606
607
        $slcFactoryId = sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory', $entityManager['name']);
608
        $factoryClass = isset($entityManager['second_level_cache']['factory']) ? $entityManager['second_level_cache']['factory'] : '%doctrine.orm.second_level_cache.default_cache_factory.class%';
609
610
        $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]);
611
612
        $slcFactoryDef = $container
613
            ->setDefinition($slcFactoryId, $definition);
614
615
        if (isset($entityManager['second_level_cache']['regions'])) {
616
            foreach ($entityManager['second_level_cache']['regions'] as $name => $region) {
617
                $regionRef  = null;
618
                $regionType = $region['type'];
619
620
                if ($regionType === 'service') {
621
                    $regionId  = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
622
                    $regionRef = new Reference($region['service']);
623
624
                    $container->setAlias($regionId, new Alias($region['service'], false));
625
                }
626
627
                if ($regionType === 'default' || $regionType === 'filelock') {
628
                    $regionId   = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
629
                    $driverName = sprintf('second_level_cache.region.%s_driver', $name);
630
                    $driverMap  = $region['cache_driver'];
631
                    $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
632
                    $regionRef  = new Reference($regionId);
633
634
                    $container
635
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%'))
636
                        ->setArguments([$name, new Reference($driverId), $region['lifetime']]);
637
                }
638
639
                if ($regionType === 'filelock') {
640
                    $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock', $entityManager['name'], $name);
641
642
                    $container
643
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%'))
644
                        ->setArguments([$regionRef, $region['lock_path'], $region['lock_lifetime']]);
645
646
                    $regionRef = new Reference($regionId);
647
                    $regionsDef->addMethodCall('getLockLifetime', [$name, $region['lock_lifetime']]);
648
                }
649
650
                $regionsDef->addMethodCall('setLifetime', [$name, $region['lifetime']]);
651
                $slcFactoryDef->addMethodCall('setRegion', [$regionRef]);
652
            }
653
        }
654
655
        if ($entityManager['second_level_cache']['log_enabled']) {
656
            $loggerChainId   = sprintf('doctrine.orm.%s_second_level_cache.logger_chain', $entityManager['name']);
657
            $loggerStatsId   = sprintf('doctrine.orm.%s_second_level_cache.logger_statistics', $entityManager['name']);
658
            $loggerChaingDef = $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%'));
659
            $loggerStatsDef  = $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%'));
660
661
            $loggerChaingDef->addMethodCall('setLogger', ['statistics', $loggerStatsDef]);
662
            $configDef->addMethodCall('setCacheLogger', [$loggerChaingDef]);
663
664
            foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) {
665
                $loggerId  = sprintf('doctrine.orm.%s_second_level_cache.logger.%s', $entityManager['name'], $name);
666
                $loggerRef = new Reference($logger['service']);
667
668
                $container->setAlias($loggerId, new Alias($logger['service'], false));
669
                $loggerChaingDef->addMethodCall('setLogger', [$name, $loggerRef]);
670
            }
671
        }
672
673
        $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]);
674
        $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]);
675
        $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]);
676
        $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]);
677
    }
678
679
    /**
680
     * {@inheritDoc}
681
     */
682
    protected function getObjectManagerElementName($name)
683
    {
684
        return 'doctrine.orm.' . $name;
685
    }
686
687
    protected function getMappingObjectDefaultName()
688
    {
689
        return 'Entity';
690
    }
691
692
    /**
693
     * {@inheritDoc}
694
     */
695
    protected function getMappingResourceConfigDirectory()
696
    {
697
        return 'Resources/config/doctrine';
698
    }
699
700
    /**
701
     * {@inheritDoc}
702
     */
703
    protected function getMappingResourceExtension()
704
    {
705
        return 'orm';
706
    }
707
708
    /**
709
     * {@inheritDoc}
710
     */
711
    protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container)
712
    {
713
        if (! empty($driverMap['cache_provider'])) {
714
            $aliasId   = $this->getObjectManagerElementName(sprintf('%s_%s', $entityManagerName, $driverName));
715
            $serviceId = sprintf('doctrine_cache.providers.%s', $driverMap['cache_provider']);
716
717
            $container->setAlias($aliasId, new Alias($serviceId, false));
718
719
            return $aliasId;
720
        }
721
722
        return $this->adapter->loadCacheDriver($driverName, $entityManagerName, $driverMap, $container);
723
    }
724
725
    /**
726
     * Loads a configured entity managers cache drivers.
727
     *
728
     * @param array            $entityManager A configured ORM entity manager.
729
     * @param ContainerBuilder $container     A ContainerBuilder instance
730
     */
731
    protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container)
732
    {
733
        $this->loadCacheDriver('metadata_cache', $entityManager['name'], $entityManager['metadata_cache_driver'], $container);
734
        $this->loadCacheDriver('result_cache', $entityManager['name'], $entityManager['result_cache_driver'], $container);
735
        $this->loadCacheDriver('query_cache', $entityManager['name'], $entityManager['query_cache_driver'], $container);
736
    }
737
738
    /**
739
     * Loads a property info extractor for each defined entity manager.
740
     *
741
     * @param string $entityManagerName
742
     */
743
    private function loadPropertyInfoExtractor($entityManagerName, ContainerBuilder $container)
744
    {
745
        $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor', $entityManagerName), DoctrineExtractor::class);
746
        if (interface_exists(PropertyInitializableExtractorInterface::class)) {
747
            $argumentId = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName);
748
        } else {
749
            $argumentId = sprintf('doctrine.orm.%s_entity_manager.metadata_factory', $entityManagerName);
750
751
            $metadataFactoryDefinition = $container->register($argumentId, ClassMetadataFactory::class);
752
            $metadataFactoryDefinition->setFactory([
753
                new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)),
754
                'getMetadataFactory',
755
            ]);
756
            $metadataFactoryDefinition->setPublic(false);
757
        }
758
759
        $propertyExtractorDefinition->addArgument(new Reference($argumentId));
760
761
        $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]);
762
        $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]);
763
    }
764
765
    /**
766
     * Loads a validator loader for each defined entity manager.
767
     *
768
     * @param string $entityManagerName
769
     */
770
    private function loadValidatorLoader($entityManagerName, ContainerBuilder $container)
771
    {
772
        if (!class_exists(DoctrineLoader::class)) {
773
            return;
774
        }
775
776
        $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.validator_loader', $entityManagerName), DoctrineLoader::class);
777
        $propertyExtractorDefinition->addArgument(new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)));
778
779
        $propertyExtractorDefinition->addTag('validator.auto_mapper', ['priority' => -100]);
780
    }
781
782
    /**
783
     * @param array  $objectManager
784
     * @param string $cacheName
785
     */
786
    public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName)
787
    {
788
        $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName . '_driver'], $container);
789
    }
790
791
    /**
792
     * {@inheritDoc}
793
     */
794
    public function getXsdValidationBasePath()
795
    {
796
        return __DIR__ . '/../Resources/config/schema';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return __DIR__ . '/../Resources/config/schema'; (string) is incompatible with the return type of the parent method Symfony\Component\Depend...etXsdValidationBasePath of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
797
    }
798
799
    /**
800
     * {@inheritDoc}
801
     */
802
    public function getNamespace()
803
    {
804
        return 'http://symfony.com/schema/dic/doctrine';
805
    }
806
807
    /**
808
     * {@inheritDoc}
809
     */
810
    public function getConfiguration(array $config, ContainerBuilder $container)
811
    {
812
        return new Configuration($container->getParameter('kernel.debug'));
813
    }
814
}
815