Completed
Pull Request — master (#892)
by Andreas
02:25
created

DoctrineExtension::getXsdValidationBasePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
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\Form\Type\DoctrineType;
14
use Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware;
15
use Symfony\Bridge\Doctrine\PropertyInfo\DoctrineExtractor;
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\DefinitionDecorator;
22
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
23
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
24
use Symfony\Component\DependencyInjection\Reference;
25
use Symfony\Component\DependencyInjection\ServiceLocator;
26
use Symfony\Component\Form\AbstractType;
27
use Symfony\Component\Messenger\MessageBusInterface;
28
use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface;
29
use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface;
30
31
/**
32
 * DoctrineExtension is an extension for the Doctrine DBAL and ORM library.
33
 */
34
class DoctrineExtension extends AbstractDoctrineExtension
35
{
36
    /** @var string */
37
    private $defaultConnection;
38
39
    /** @var SymfonyBridgeAdapter */
40
    private $adapter;
41
42
    public function __construct(SymfonyBridgeAdapter $adapter = null)
43
    {
44
        $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm');
45
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50
    public function load(array $configs, ContainerBuilder $container)
51
    {
52
        $configuration = $this->getConfiguration($configs, $container);
53
        $config        = $this->processConfiguration($configuration, $configs);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 52 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...
54
55
        $this->adapter->loadServicesConfiguration($container);
56
57
        if (! empty($config['dbal'])) {
58
            $this->dbalLoad($config['dbal'], $container);
59
        }
60
61
        if (empty($config['orm'])) {
62
            return;
63
        }
64
65
        if (empty($config['dbal'])) {
66
            throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.');
67
        }
68
69
        if (! class_exists(Version::class)) {
70
            throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.');
71
        }
72
73
        $this->ormLoad($config['orm'], $container);
74
    }
75
76
    /**
77
     * Loads the DBAL configuration.
78
     *
79
     * Usage example:
80
     *
81
     *      <doctrine:dbal id="myconn" dbname="sfweb" user="root" />
82
     *
83
     * @param array            $config    An array of configuration settings
84
     * @param ContainerBuilder $container A ContainerBuilder instance
85
     */
86
    protected function dbalLoad(array $config, ContainerBuilder $container)
87
    {
88
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
89
        $loader->load('dbal.xml');
90
91
        if (empty($config['default_connection'])) {
92
            $keys                         = array_keys($config['connections']);
93
            $config['default_connection'] = reset($keys);
94
        }
95
96
        $this->defaultConnection = $config['default_connection'];
97
98
        $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection));
99
        $container->getAlias('database_connection')->setPublic(true);
100
        $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false));
101
102
        $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']);
103
104
        $connections = [];
105
106
        foreach (array_keys($config['connections']) as $name) {
107
            $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name);
108
        }
109
110
        $container->setParameter('doctrine.connections', $connections);
111
        $container->setParameter('doctrine.default_connection', $this->defaultConnection);
112
113
        foreach ($config['connections'] as $name => $connection) {
114
            $this->loadDbalConnection($name, $connection, $container);
115
        }
116
    }
117
118
    /**
119
     * Loads a configured DBAL connection.
120
     *
121
     * @param string           $name       The name of the connection
122
     * @param array            $connection A dbal connection configuration.
123
     * @param ContainerBuilder $container  A ContainerBuilder instance
124
     */
125
    protected function loadDbalConnection($name, array $connection, ContainerBuilder $container)
126
    {
127
        $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration'));
128
        $logger        = null;
129
        if ($connection['logging']) {
130
            $logger = new Reference('doctrine.dbal.logger');
131
        }
132
        unset($connection['logging']);
133
        if ($connection['profiling']) {
134
            $profilingLoggerId = 'doctrine.dbal.logger.profiling.' . $name;
135
            $container->setDefinition($profilingLoggerId, new ChildDefinition('doctrine.dbal.logger.profiling'));
136
            $profilingLogger = new Reference($profilingLoggerId);
137
            $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]);
138
139
            if ($logger !== null) {
140
                $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain');
141
                $chainLogger->addMethodCall('addLogger', [$profilingLogger]);
142
143
                $loggerId = 'doctrine.dbal.logger.chain.' . $name;
144
                $container->setDefinition($loggerId, $chainLogger);
145
                $logger = new Reference($loggerId);
146
            } else {
147
                $logger = $profilingLogger;
148
            }
149
        }
150
        unset($connection['profiling']);
151
152
        if (isset($connection['auto_commit'])) {
153
            $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]);
154
        }
155
156
        unset($connection['auto_commit']);
157
158
        if (isset($connection['schema_filter']) && $connection['schema_filter']) {
159
            $configuration->addMethodCall('setFilterSchemaAssetsExpression', [$connection['schema_filter']]);
160
        }
161
162
        unset($connection['schema_filter']);
163
164
        if ($logger) {
165
            $configuration->addMethodCall('setSQLLogger', [$logger]);
166
        }
167
168
        // event manager
169
        $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager'));
170
171
        // connection
172
        $options = $this->getConnectionOptions($connection);
173
174
        $def = $container
175
            ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection'))
176
            ->setPublic(true)
177
            ->setArguments([
178
                $options,
179
                new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)),
180
                new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)),
181
                $connection['mapping_types'],
182
            ]);
183
184
        // Set class in case "wrapper_class" option was used to assist IDEs
185
        if (isset($options['wrapperClass'])) {
186
            $def->setClass($options['wrapperClass']);
187
        }
188
189
        if (! empty($connection['use_savepoints'])) {
190
            $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]);
191
        }
192
193
        // Create a shard_manager for this connection
194
        if (! isset($options['shards'])) {
195
            return;
196
        }
197
198
        $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]);
199
        $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition);
200
    }
201
202
    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...
203
    {
204
        $options = $connection;
205
206
        if (isset($options['platform_service'])) {
207
            $options['platform'] = new Reference($options['platform_service']);
208
            unset($options['platform_service']);
209
        }
210
        unset($options['mapping_types']);
211
212
        if (isset($options['shard_choser_service'])) {
213
            $options['shard_choser'] = new Reference($options['shard_choser_service']);
214
            unset($options['shard_choser_service']);
215
        }
216
217
        foreach ([
218
            'options' => 'driverOptions',
219
            'driver_class' => 'driverClass',
220
            'wrapper_class' => 'wrapperClass',
221
            'keep_slave' => 'keepSlave',
222
            'shard_choser' => 'shardChoser',
223
            'shard_manager_class' => 'shardManagerClass',
224
            'server_version' => 'serverVersion',
225
            'default_table_options' => 'defaultTableOptions',
226
        ] as $old => $new) {
227
            if (! isset($options[$old])) {
228
                continue;
229
            }
230
231
            $options[$new] = $options[$old];
232
            unset($options[$old]);
233
        }
234
235
        if (! empty($options['slaves']) && ! empty($options['shards'])) {
236
            throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together');
237
        }
238
239
        if (! empty($options['slaves'])) {
240
            $nonRewrittenKeys = [
241
                'driver' => true,
242
                'driverOptions' => true,
243
                'driverClass' => true,
244
                'wrapperClass' => true,
245
                'keepSlave' => true,
246
                'shardChoser' => true,
247
                'platform' => true,
248
                'slaves' => true,
249
                'master' => true,
250
                'shards' => true,
251
                'serverVersion' => true,
252
                // included by safety but should have been unset already
253
                'logging' => true,
254
                'profiling' => true,
255
                'mapping_types' => true,
256
                'platform_service' => true,
257
            ];
258 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...
259
                if (isset($nonRewrittenKeys[$key])) {
260
                    continue;
261
                }
262
                $options['master'][$key] = $value;
263
                unset($options[$key]);
264
            }
265
            if (empty($options['wrapperClass'])) {
266
                // Change the wrapper class only if the user does not already forced using a custom one.
267
                $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection';
268
            }
269
        } else {
270
            unset($options['slaves']);
271
        }
272
273
        if (! empty($options['shards'])) {
274
            $nonRewrittenKeys = [
275
                'driver' => true,
276
                'driverOptions' => true,
277
                'driverClass' => true,
278
                'wrapperClass' => true,
279
                'keepSlave' => true,
280
                'shardChoser' => true,
281
                'platform' => true,
282
                'slaves' => true,
283
                'global' => true,
284
                'shards' => true,
285
                'serverVersion' => true,
286
                // included by safety but should have been unset already
287
                'logging' => true,
288
                'profiling' => true,
289
                'mapping_types' => true,
290
                'platform_service' => true,
291
            ];
292 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...
293
                if (isset($nonRewrittenKeys[$key])) {
294
                    continue;
295
                }
296
                $options['global'][$key] = $value;
297
                unset($options[$key]);
298
            }
299
            if (empty($options['wrapperClass'])) {
300
                // Change the wrapper class only if the user does not already forced using a custom one.
301
                $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection';
302
            }
303
            if (empty($options['shardManagerClass'])) {
304
                // Change the shard manager class only if the user does not already forced using a custom one.
305
                $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager';
306
            }
307
        } else {
308
            unset($options['shards']);
309
        }
310
311
        return $options;
312
    }
313
314
    /**
315
     * Loads the Doctrine ORM configuration.
316
     *
317
     * Usage example:
318
     *
319
     *     <doctrine:orm id="mydm" connection="myconn" />
320
     *
321
     * @param array            $config    An array of configuration settings
322
     * @param ContainerBuilder $container A ContainerBuilder instance
323
     */
324
    protected function ormLoad(array $config, ContainerBuilder $container)
325
    {
326
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
327
        $loader->load('orm.xml');
328
329
        $entityManagers = [];
330
        foreach (array_keys($config['entity_managers']) as $name) {
331
            $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name);
332
        }
333
        $container->setParameter('doctrine.entity_managers', $entityManagers);
334
335
        if (empty($config['default_entity_manager'])) {
336
            $tmp                              = array_keys($entityManagers);
337
            $config['default_entity_manager'] = reset($tmp);
338
        }
339
        $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']);
340
341
        $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace'];
342
        foreach ($options as $key) {
343
            $container->setParameter('doctrine.orm.' . $key, $config[$key]);
344
        }
345
346
        $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager']));
347
        $container->getAlias('doctrine.orm.entity_manager')->setPublic(true);
348
349
        $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles'));
350
351
        foreach ($config['entity_managers'] as $name => $entityManager) {
352
            $entityManager['name'] = $name;
353
            $this->loadOrmEntityManager($entityManager, $container);
354
355
            $this->loadPropertyInfoExtractor($name, $container);
356
        }
357
358
        if ($config['resolve_target_entities']) {
359
            $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity');
360
            foreach ($config['resolve_target_entities'] as $name => $implementation) {
361
                $def->addMethodCall('addResolveTargetEntity', [
362
                    $name,
363
                    $implementation,
364
                    [],
365
                ]);
366
            }
367
368
            $def->addTag('doctrine.event_subscriber');
369
        }
370
371
        $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class)
372
            ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG);
373
374
        // If the Messenger component is installed and the doctrine transaction middleware is available, wire it:
375
        if (interface_exists(MessageBusInterface::class) && class_exists(DoctrineTransactionMiddleware::class)) {
376
            $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
377
            $loader->load('messenger.xml');
378
        }
379
380
        /*
381
         * Compatibility for Symfony 3.2 and lower: gives the service a default argument.
382
         * When DoctrineBundle requires 3.3 or higher, this can be moved to an anonymous
383
         * service in orm.xml.
384
         *
385
         * This is replaced with a true locator by ServiceRepositoryCompilerPass.
386
         * This makes that pass technically optional (good for tests).
387
         */
388
        // @todo cleanup
389
        if (! class_exists(ServiceLocator::class)) {
390
            return;
391
        }
392
393
        $container->getDefinition('doctrine.orm.container_repository_factory')
394
            ->replaceArgument(0, (new Definition(ServiceLocator::class))->setArgument(0, []));
395
    }
396
397
    /**
398
     * Loads a configured ORM entity manager.
399
     *
400
     * @param array            $entityManager A configured ORM entity manager.
401
     * @param ContainerBuilder $container     A ContainerBuilder instance
402
     */
403
    protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container)
404
    {
405
        $ormConfigDef = $container->setDefinition(sprintf('doctrine.orm.%s_configuration', $entityManager['name']), new ChildDefinition('doctrine.orm.configuration'));
406
407
        $this->loadOrmEntityManagerMappingInformation($entityManager, $ormConfigDef, $container);
408
        $this->loadOrmCacheDrivers($entityManager, $container);
409
410
        if (isset($entityManager['entity_listener_resolver']) && $entityManager['entity_listener_resolver']) {
411
            $container->setAlias(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $entityManager['entity_listener_resolver']);
412
        } else {
413
            $definition = new Definition('%doctrine.orm.entity_listener_resolver.class%');
414
            $definition->addArgument(new Reference('service_container'));
415
            $container->setDefinition(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name']), $definition);
416
        }
417
418
        $methods = [
419
            'setMetadataCacheImpl' => new Reference(sprintf('doctrine.orm.%s_metadata_cache', $entityManager['name'])),
420
            'setQueryCacheImpl' => new Reference(sprintf('doctrine.orm.%s_query_cache', $entityManager['name'])),
421
            'setResultCacheImpl' => new Reference(sprintf('doctrine.orm.%s_result_cache', $entityManager['name'])),
422
            'setMetadataDriverImpl' => new Reference('doctrine.orm.' . $entityManager['name'] . '_metadata_driver'),
423
            'setProxyDir' => '%doctrine.orm.proxy_dir%',
424
            'setProxyNamespace' => '%doctrine.orm.proxy_namespace%',
425
            'setAutoGenerateProxyClasses' => '%doctrine.orm.auto_generate_proxy_classes%',
426
            'setClassMetadataFactoryName' => $entityManager['class_metadata_factory_name'],
427
            'setDefaultRepositoryClassName' => $entityManager['default_repository_class'],
428
            'setNamingStrategy' => new Reference($entityManager['naming_strategy']),
429
            'setQuoteStrategy' => new Reference($entityManager['quote_strategy']),
430
            'setEntityListenerResolver' => new Reference(sprintf('doctrine.orm.%s_entity_listener_resolver', $entityManager['name'])),
431
        ];
432
433
        $listenerId        = sprintf('doctrine.orm.%s_listeners.attach_entity_listeners', $entityManager['name']);
434
        $listenerDef       = $container->setDefinition($listenerId, new Definition('%doctrine.orm.listeners.attach_entity_listeners.class%'));
435
        $listenerTagParams = ['event' => 'loadClassMetadata'];
436
        if (isset($entityManager['connection'])) {
437
            $listenerTagParams['connection'] = $entityManager['connection'];
438
        }
439
        $listenerDef->addTag('doctrine.event_listener', $listenerTagParams);
440
441
        if (isset($entityManager['second_level_cache'])) {
442
            $this->loadOrmSecondLevelCache($entityManager, $ormConfigDef, $container);
443
        }
444
445
        if ($entityManager['repository_factory']) {
446
            $methods['setRepositoryFactory'] = new Reference($entityManager['repository_factory']);
447
        }
448
449
        foreach ($methods as $method => $arg) {
450
            $ormConfigDef->addMethodCall($method, [$arg]);
451
        }
452
453
        foreach ($entityManager['hydrators'] as $name => $class) {
454
            $ormConfigDef->addMethodCall('addCustomHydrationMode', [$name, $class]);
455
        }
456
457
        if (! empty($entityManager['dql'])) {
458
            foreach ($entityManager['dql']['string_functions'] as $name => $function) {
459
                $ormConfigDef->addMethodCall('addCustomStringFunction', [$name, $function]);
460
            }
461
            foreach ($entityManager['dql']['numeric_functions'] as $name => $function) {
462
                $ormConfigDef->addMethodCall('addCustomNumericFunction', [$name, $function]);
463
            }
464
            foreach ($entityManager['dql']['datetime_functions'] as $name => $function) {
465
                $ormConfigDef->addMethodCall('addCustomDatetimeFunction', [$name, $function]);
466
            }
467
        }
468
469
        $enabledFilters    = [];
470
        $filtersParameters = [];
471
        foreach ($entityManager['filters'] as $name => $filter) {
472
            $ormConfigDef->addMethodCall('addFilter', [$name, $filter['class']]);
473
            if ($filter['enabled']) {
474
                $enabledFilters[] = $name;
475
            }
476
            if (! $filter['parameters']) {
477
                continue;
478
            }
479
480
            $filtersParameters[$name] = $filter['parameters'];
481
        }
482
483
        $managerConfiguratorName = sprintf('doctrine.orm.%s_manager_configurator', $entityManager['name']);
484
        $container
485
            ->setDefinition($managerConfiguratorName, new ChildDefinition('doctrine.orm.manager_configurator.abstract'))
486
            ->replaceArgument(0, $enabledFilters)
487
            ->replaceArgument(1, $filtersParameters);
488
489
        if (! isset($entityManager['connection'])) {
490
            $entityManager['connection'] = $this->defaultConnection;
491
        }
492
493
        $container
494
            ->setDefinition(sprintf('doctrine.orm.%s_entity_manager', $entityManager['name']), new ChildDefinition('doctrine.orm.entity_manager.abstract'))
495
            ->setPublic(true)
496
            ->setArguments([
497
                new Reference(sprintf('doctrine.dbal.%s_connection', $entityManager['connection'])),
498
                new Reference(sprintf('doctrine.orm.%s_configuration', $entityManager['name'])),
499
            ])
500
            ->setConfigurator([new Reference($managerConfiguratorName), 'configure']);
501
502
        $container->setAlias(
503
            sprintf('doctrine.orm.%s_entity_manager.event_manager', $entityManager['name']),
504
            new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $entityManager['connection']), false)
505
        );
506
507
        if (! isset($entityManager['entity_listeners'])) {
508
            return;
509
        }
510
511
        if (! isset($listenerDef)) {
512
            throw new InvalidArgumentException('Entity listeners configuration requires doctrine-orm 2.5.0 or newer');
513
        }
514
515
        $entities = $entityManager['entity_listeners']['entities'];
516
517
        foreach ($entities as $entityListenerClass => $entity) {
518
            foreach ($entity['listeners'] as $listenerClass => $listener) {
519
                foreach ($listener['events'] as $listenerEvent) {
520
                    $listenerEventName = $listenerEvent['type'];
521
                    $listenerMethod    = $listenerEvent['method'];
522
523
                    $listenerDef->addMethodCall('addEntityListener', [
524
                        $entityListenerClass,
525
                        $listenerClass,
526
                        $listenerEventName,
527
                        $listenerMethod,
528
                    ]);
529
                }
530
            }
531
        }
532
    }
533
534
    /**
535
     * Loads an ORM entity managers bundle mapping information.
536
     *
537
     * There are two distinct configuration possibilities for mapping information:
538
     *
539
     * 1. Specify a bundle and optionally details where the entity and mapping information reside.
540
     * 2. Specify an arbitrary mapping location.
541
     *
542
     * @param array            $entityManager A configured ORM entity manager
543
     * @param Definition       $ormConfigDef  A Definition instance
544
     * @param ContainerBuilder $container     A ContainerBuilder instance
545
     *
546
     * @example
547
     *
548
     *  doctrine.orm:
549
     *     mappings:
550
     *         MyBundle1: ~
551
     *         MyBundle2: yml
552
     *         MyBundle3: { type: annotation, dir: Entities/ }
553
     *         MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping }
554
     *         MyBundle5:
555
     *             type: yml
556
     *             dir: bundle-mappings/
557
     *             alias: BundleAlias
558
     *         arbitrary_key:
559
     *             type: xml
560
     *             dir: %kernel.root_dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities
561
     *             prefix: DoctrineExtensions\Entities\
562
     *             alias: DExt
563
     *
564
     * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but
565
     * in the mappings key everything except alias is a required argument.
566
     */
567
    protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
568
    {
569
        // reset state of drivers and alias map. They are only used by this methods and children.
570
        $this->drivers  = [];
571
        $this->aliasMap = [];
572
573
        $this->loadMappingInformation($entityManager, $container);
574
        $this->registerMappingDrivers($entityManager, $container);
575
576
        $ormConfigDef->addMethodCall('setEntityNamespaces', [$this->aliasMap]);
577
    }
578
579
    /**
580
     * Loads an ORM second level cache bundle mapping information.
581
     *
582
     * @param array            $entityManager A configured ORM entity manager
583
     * @param Definition       $ormConfigDef  A Definition instance
584
     * @param ContainerBuilder $container     A ContainerBuilder instance
585
     *
586
     * @example
587
     *  entity_managers:
588
     *      default:
589
     *          second_level_cache:
590
     *              region_cache_driver: apc
591
     *              log_enabled: true
592
     *              regions:
593
     *                  my_service_region:
594
     *                      type: service
595
     *                      service : "my_service_region"
596
     *
597
     *                  my_query_region:
598
     *                      lifetime: 300
599
     *                      cache_driver: array
600
     *                      type: filelock
601
     *
602
     *                  my_entity_region:
603
     *                      lifetime: 600
604
     *                      cache_driver:
605
     *                          type: apc
606
     */
607
    protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container)
608
    {
609
        $driverId = null;
610
        $enabled  = $entityManager['second_level_cache']['enabled'];
611
612
        if (isset($entityManager['second_level_cache']['region_cache_driver'])) {
613
            $driverName = 'second_level_cache.region_cache_driver';
614
            $driverMap  = $entityManager['second_level_cache']['region_cache_driver'];
615
            $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
616
        }
617
618
        $configId   = sprintf('doctrine.orm.%s_second_level_cache.cache_configuration', $entityManager['name']);
619
        $regionsId  = sprintf('doctrine.orm.%s_second_level_cache.regions_configuration', $entityManager['name']);
620
        $driverId   = $driverId ?: sprintf('doctrine.orm.%s_second_level_cache.region_cache_driver', $entityManager['name']);
621
        $configDef  = $container->setDefinition($configId, new Definition('%doctrine.orm.second_level_cache.cache_configuration.class%'));
622
        $regionsDef = $container->setDefinition($regionsId, new Definition('%doctrine.orm.second_level_cache.regions_configuration.class%'));
623
624
        $slcFactoryId = sprintf('doctrine.orm.%s_second_level_cache.default_cache_factory', $entityManager['name']);
625
        $factoryClass = isset($entityManager['second_level_cache']['factory']) ? $entityManager['second_level_cache']['factory'] : '%doctrine.orm.second_level_cache.default_cache_factory.class%';
626
627
        $definition = new Definition($factoryClass, [new Reference($regionsId), new Reference($driverId)]);
628
629
        $slcFactoryDef = $container
630
            ->setDefinition($slcFactoryId, $definition);
631
632
        if (isset($entityManager['second_level_cache']['regions'])) {
633
            foreach ($entityManager['second_level_cache']['regions'] as $name => $region) {
634
                $regionRef  = null;
635
                $regionType = $region['type'];
636
637
                if ($regionType === 'service') {
638
                    $regionId  = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
639
                    $regionRef = new Reference($region['service']);
640
641
                    $container->setAlias($regionId, new Alias($region['service'], false));
642
                }
643
644
                if ($regionType === 'default' || $regionType === 'filelock') {
645
                    $regionId   = sprintf('doctrine.orm.%s_second_level_cache.region.%s', $entityManager['name'], $name);
646
                    $driverName = sprintf('second_level_cache.region.%s_driver', $name);
647
                    $driverMap  = $region['cache_driver'];
648
                    $driverId   = $this->loadCacheDriver($driverName, $entityManager['name'], $driverMap, $container);
649
                    $regionRef  = new Reference($regionId);
650
651
                    $container
652
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.default_region.class%'))
653
                        ->setArguments([$name, new Reference($driverId), $region['lifetime']]);
654
                }
655
656
                if ($regionType === 'filelock') {
657
                    $regionId = sprintf('doctrine.orm.%s_second_level_cache.region.%s_filelock', $entityManager['name'], $name);
658
659
                    $container
660
                        ->setDefinition($regionId, new Definition('%doctrine.orm.second_level_cache.filelock_region.class%'))
661
                        ->setArguments([$regionRef, $region['lock_path'], $region['lock_lifetime']]);
662
663
                    $regionRef = new Reference($regionId);
664
                    $regionsDef->addMethodCall('getLockLifetime', [$name, $region['lock_lifetime']]);
665
                }
666
667
                $regionsDef->addMethodCall('setLifetime', [$name, $region['lifetime']]);
668
                $slcFactoryDef->addMethodCall('setRegion', [$regionRef]);
669
            }
670
        }
671
672
        if ($entityManager['second_level_cache']['log_enabled']) {
673
            $loggerChainId   = sprintf('doctrine.orm.%s_second_level_cache.logger_chain', $entityManager['name']);
674
            $loggerStatsId   = sprintf('doctrine.orm.%s_second_level_cache.logger_statistics', $entityManager['name']);
675
            $loggerChaingDef = $container->setDefinition($loggerChainId, new Definition('%doctrine.orm.second_level_cache.logger_chain.class%'));
676
            $loggerStatsDef  = $container->setDefinition($loggerStatsId, new Definition('%doctrine.orm.second_level_cache.logger_statistics.class%'));
677
678
            $loggerChaingDef->addMethodCall('setLogger', ['statistics', $loggerStatsDef]);
679
            $configDef->addMethodCall('setCacheLogger', [$loggerChaingDef]);
680
681
            foreach ($entityManager['second_level_cache']['loggers'] as $name => $logger) {
682
                $loggerId  = sprintf('doctrine.orm.%s_second_level_cache.logger.%s', $entityManager['name'], $name);
683
                $loggerRef = new Reference($logger['service']);
684
685
                $container->setAlias($loggerId, new Alias($logger['service'], false));
686
                $loggerChaingDef->addMethodCall('setLogger', [$name, $loggerRef]);
687
            }
688
        }
689
690
        $configDef->addMethodCall('setCacheFactory', [$slcFactoryDef]);
691
        $configDef->addMethodCall('setRegionsConfiguration', [$regionsDef]);
692
        $ormConfigDef->addMethodCall('setSecondLevelCacheEnabled', [$enabled]);
693
        $ormConfigDef->addMethodCall('setSecondLevelCacheConfiguration', [$configDef]);
694
    }
695
696
    /**
697
     * {@inheritDoc}
698
     */
699
    protected function getObjectManagerElementName($name)
700
    {
701
        return 'doctrine.orm.' . $name;
702
    }
703
704
    protected function getMappingObjectDefaultName()
705
    {
706
        return 'Entity';
707
    }
708
709
    /**
710
     * {@inheritDoc}
711
     */
712
    protected function getMappingResourceConfigDirectory()
713
    {
714
        return 'Resources/config/doctrine';
715
    }
716
717
    /**
718
     * {@inheritDoc}
719
     */
720
    protected function getMappingResourceExtension()
721
    {
722
        return 'orm';
723
    }
724
725
    /**
726
     * {@inheritDoc}
727
     */
728
    protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container)
729
    {
730
        if (! empty($driverMap['cache_provider'])) {
731
            $aliasId   = $this->getObjectManagerElementName(sprintf('%s_%s', $entityManagerName, $driverName));
732
            $serviceId = sprintf('doctrine_cache.providers.%s', $driverMap['cache_provider']);
733
734
            $container->setAlias($aliasId, new Alias($serviceId, false));
735
736
            return $aliasId;
737
        }
738
739
        return $this->adapter->loadCacheDriver($driverName, $entityManagerName, $driverMap, $container);
740
    }
741
742
    /**
743
     * Loads a configured entity managers cache drivers.
744
     *
745
     * @param array            $entityManager A configured ORM entity manager.
746
     * @param ContainerBuilder $container     A ContainerBuilder instance
747
     */
748
    protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container)
749
    {
750
        $this->loadCacheDriver('metadata_cache', $entityManager['name'], $entityManager['metadata_cache_driver'], $container);
751
        $this->loadCacheDriver('result_cache', $entityManager['name'], $entityManager['result_cache_driver'], $container);
752
        $this->loadCacheDriver('query_cache', $entityManager['name'], $entityManager['query_cache_driver'], $container);
753
    }
754
755
    /**
756
     * Loads a property info extractor for each defined entity manager.
757
     *
758
     * @param string $entityManagerName
759
     */
760
    private function loadPropertyInfoExtractor($entityManagerName, ContainerBuilder $container)
761
    {
762
        $propertyExtractorDefinition = $container->register(sprintf('doctrine.orm.%s_entity_manager.property_info_extractor', $entityManagerName), DoctrineExtractor::class);
763
        if (interface_exists(PropertyInitializableExtractorInterface::class)) {
764
            $argumentId = sprintf('doctrine.orm.%s_entity_manager', $entityManagerName);
765
        } else {
766
            $argumentId = sprintf('doctrine.orm.%s_entity_manager.metadata_factory', $entityManagerName);
767
768
            $metadataFactoryDefinition = $container->register($argumentId, ClassMetadataFactory::class);
769
            $metadataFactoryDefinition->setFactory([
770
                new Reference(sprintf('doctrine.orm.%s_entity_manager', $entityManagerName)),
771
                'getMetadataFactory',
772
            ]);
773
            $metadataFactoryDefinition->setPublic(false);
774
        }
775
776
        $propertyExtractorDefinition->addArgument(new Reference($argumentId));
777
778
        $propertyExtractorDefinition->addTag('property_info.list_extractor', ['priority' => -1001]);
779
        $propertyExtractorDefinition->addTag('property_info.type_extractor', ['priority' => -999]);
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