Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like DoctrineExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DoctrineExtension, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
35 | class DoctrineExtension extends AbstractDoctrineExtension |
||
36 | { |
||
37 | /** @var string */ |
||
38 | private $defaultConnection; |
||
39 | |||
40 | /** @var SymfonyBridgeAdapter */ |
||
41 | private $adapter; |
||
42 | |||
43 | public function __construct(SymfonyBridgeAdapter $adapter = null) |
||
44 | { |
||
45 | $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm'); |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * {@inheritDoc} |
||
50 | */ |
||
51 | public function load(array $configs, ContainerBuilder $container) |
||
52 | { |
||
53 | $configuration = $this->getConfiguration($configs, $container); |
||
54 | $config = $this->processConfiguration($configuration, $configs); |
||
|
|||
55 | |||
56 | $this->adapter->loadServicesConfiguration($container); |
||
57 | |||
58 | if (! empty($config['dbal'])) { |
||
59 | $this->dbalLoad($config['dbal'], $container); |
||
60 | } |
||
61 | |||
62 | if (empty($config['orm'])) { |
||
63 | return; |
||
64 | } |
||
65 | |||
66 | if (empty($config['dbal'])) { |
||
67 | throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.'); |
||
68 | } |
||
69 | |||
70 | if (! class_exists(Version::class)) { |
||
71 | throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.'); |
||
72 | } |
||
73 | |||
74 | $this->ormLoad($config['orm'], $container); |
||
75 | } |
||
76 | |||
77 | /** |
||
78 | * Loads the DBAL configuration. |
||
79 | * |
||
80 | * Usage example: |
||
81 | * |
||
82 | * <doctrine:dbal id="myconn" dbname="sfweb" user="root" /> |
||
83 | * |
||
84 | * @param array $config An array of configuration settings |
||
85 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
86 | */ |
||
87 | protected function dbalLoad(array $config, ContainerBuilder $container) |
||
88 | { |
||
89 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
90 | $loader->load('dbal.xml'); |
||
91 | |||
92 | if (empty($config['default_connection'])) { |
||
93 | $keys = array_keys($config['connections']); |
||
94 | $config['default_connection'] = reset($keys); |
||
95 | } |
||
96 | |||
97 | $this->defaultConnection = $config['default_connection']; |
||
98 | |||
99 | $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection)); |
||
100 | $container->getAlias('database_connection')->setPublic(true); |
||
101 | $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false)); |
||
102 | |||
103 | $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']); |
||
104 | |||
105 | $connections = []; |
||
106 | |||
107 | foreach (array_keys($config['connections']) as $name) { |
||
108 | $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name); |
||
109 | } |
||
110 | |||
111 | $container->setParameter('doctrine.connections', $connections); |
||
112 | $container->setParameter('doctrine.default_connection', $this->defaultConnection); |
||
113 | |||
114 | foreach ($config['connections'] as $name => $connection) { |
||
115 | $this->loadDbalConnection($name, $connection, $container); |
||
116 | } |
||
117 | } |
||
118 | |||
119 | /** |
||
120 | * Loads a configured DBAL connection. |
||
121 | * |
||
122 | * @param string $name The name of the connection |
||
123 | * @param array $connection A dbal connection configuration. |
||
124 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
125 | */ |
||
126 | protected function loadDbalConnection($name, array $connection, ContainerBuilder $container) |
||
127 | { |
||
128 | $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration')); |
||
129 | $logger = null; |
||
130 | if ($connection['logging']) { |
||
131 | $logger = new Reference('doctrine.dbal.logger'); |
||
132 | } |
||
133 | unset($connection['logging']); |
||
134 | if ($connection['profiling']) { |
||
135 | $profilingLoggerId = 'doctrine.dbal.logger.profiling.' . $name; |
||
136 | $container->setDefinition($profilingLoggerId, new ChildDefinition('doctrine.dbal.logger.profiling')); |
||
137 | $profilingLogger = new Reference($profilingLoggerId); |
||
138 | $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]); |
||
139 | |||
140 | if ($logger !== null) { |
||
141 | $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain'); |
||
142 | $chainLogger->addMethodCall('addLogger', [$profilingLogger]); |
||
143 | |||
144 | $loggerId = 'doctrine.dbal.logger.chain.' . $name; |
||
145 | $container->setDefinition($loggerId, $chainLogger); |
||
146 | $logger = new Reference($loggerId); |
||
147 | } else { |
||
148 | $logger = $profilingLogger; |
||
149 | } |
||
150 | } |
||
151 | unset($connection['profiling']); |
||
152 | |||
153 | if (isset($connection['auto_commit'])) { |
||
154 | $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]); |
||
155 | } |
||
156 | |||
157 | unset($connection['auto_commit']); |
||
158 | |||
159 | if (isset($connection['schema_filter']) && $connection['schema_filter']) { |
||
160 | if (method_exists(\Doctrine\DBAL\Configuration::class, 'setSchemaAssetsFilter')) { |
||
161 | $definition = new Definition(RegexSchemaAssetFilter::class, [$connection['schema_filter']]); |
||
162 | $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]); |
||
163 | $container->setDefinition(sprintf('doctrine.dbal.%s_regex_schema_filter', $name), $definition); |
||
164 | } else { |
||
165 | // backwards compatibility with dbal < 2.9 |
||
166 | $configuration->addMethodCall('setFilterSchemaAssetsExpression', [$connection['schema_filter']]); |
||
167 | } |
||
168 | } |
||
169 | |||
170 | unset($connection['schema_filter']); |
||
171 | |||
172 | if ($logger) { |
||
173 | $configuration->addMethodCall('setSQLLogger', [$logger]); |
||
174 | } |
||
175 | |||
176 | // event manager |
||
177 | $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager')); |
||
178 | |||
179 | // connection |
||
180 | $options = $this->getConnectionOptions($connection); |
||
181 | |||
182 | $def = $container |
||
183 | ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection')) |
||
184 | ->setPublic(true) |
||
185 | ->setArguments([ |
||
186 | $options, |
||
187 | new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)), |
||
188 | new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)), |
||
189 | $connection['mapping_types'], |
||
190 | ]); |
||
191 | |||
192 | // Set class in case "wrapper_class" option was used to assist IDEs |
||
193 | if (isset($options['wrapperClass'])) { |
||
194 | $def->setClass($options['wrapperClass']); |
||
195 | } |
||
196 | |||
197 | if (! empty($connection['use_savepoints'])) { |
||
198 | $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]); |
||
199 | } |
||
200 | |||
201 | // Create a shard_manager for this connection |
||
202 | if (! isset($options['shards'])) { |
||
203 | return; |
||
204 | } |
||
205 | |||
206 | $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]); |
||
207 | $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition); |
||
208 | } |
||
209 | |||
210 | protected function getConnectionOptions($connection) |
||
211 | { |
||
212 | $options = $connection; |
||
213 | |||
214 | if (isset($options['platform_service'])) { |
||
215 | $options['platform'] = new Reference($options['platform_service']); |
||
216 | unset($options['platform_service']); |
||
217 | } |
||
218 | unset($options['mapping_types']); |
||
219 | |||
220 | if (isset($options['shard_choser_service'])) { |
||
221 | $options['shard_choser'] = new Reference($options['shard_choser_service']); |
||
222 | unset($options['shard_choser_service']); |
||
223 | } |
||
224 | |||
225 | foreach ([ |
||
226 | 'options' => 'driverOptions', |
||
227 | 'driver_class' => 'driverClass', |
||
228 | 'wrapper_class' => 'wrapperClass', |
||
229 | 'keep_slave' => 'keepSlave', |
||
230 | 'shard_choser' => 'shardChoser', |
||
231 | 'shard_manager_class' => 'shardManagerClass', |
||
232 | 'server_version' => 'serverVersion', |
||
233 | 'default_table_options' => 'defaultTableOptions', |
||
234 | ] as $old => $new) { |
||
235 | if (! isset($options[$old])) { |
||
236 | continue; |
||
237 | } |
||
238 | |||
239 | $options[$new] = $options[$old]; |
||
240 | unset($options[$old]); |
||
241 | } |
||
242 | |||
243 | if (! empty($options['slaves']) && ! empty($options['shards'])) { |
||
244 | throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together'); |
||
245 | } |
||
246 | |||
247 | if (! empty($options['slaves'])) { |
||
248 | $nonRewrittenKeys = [ |
||
249 | 'driver' => true, |
||
250 | 'driverOptions' => true, |
||
251 | 'driverClass' => true, |
||
252 | 'wrapperClass' => true, |
||
253 | 'keepSlave' => true, |
||
254 | 'shardChoser' => true, |
||
255 | 'platform' => true, |
||
256 | 'slaves' => true, |
||
257 | 'master' => true, |
||
258 | 'shards' => true, |
||
259 | 'serverVersion' => true, |
||
260 | 'defaultTableOptions' => true, |
||
261 | // included by safety but should have been unset already |
||
262 | 'logging' => true, |
||
263 | 'profiling' => true, |
||
264 | 'mapping_types' => true, |
||
265 | 'platform_service' => true, |
||
266 | ]; |
||
267 | View Code Duplication | foreach ($options as $key => $value) { |
|
268 | if (isset($nonRewrittenKeys[$key])) { |
||
269 | continue; |
||
270 | } |
||
271 | $options['master'][$key] = $value; |
||
272 | unset($options[$key]); |
||
273 | } |
||
274 | if (empty($options['wrapperClass'])) { |
||
275 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
276 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection'; |
||
277 | } |
||
278 | } else { |
||
279 | unset($options['slaves']); |
||
280 | } |
||
281 | |||
282 | if (! empty($options['shards'])) { |
||
283 | $nonRewrittenKeys = [ |
||
284 | 'driver' => true, |
||
285 | 'driverOptions' => true, |
||
286 | 'driverClass' => true, |
||
287 | 'wrapperClass' => true, |
||
288 | 'keepSlave' => true, |
||
289 | 'shardChoser' => true, |
||
290 | 'platform' => true, |
||
291 | 'slaves' => true, |
||
292 | 'global' => true, |
||
293 | 'shards' => true, |
||
294 | 'serverVersion' => true, |
||
295 | 'defaultTableOptions' => true, |
||
296 | // included by safety but should have been unset already |
||
297 | 'logging' => true, |
||
298 | 'profiling' => true, |
||
299 | 'mapping_types' => true, |
||
300 | 'platform_service' => true, |
||
301 | ]; |
||
302 | View Code Duplication | foreach ($options as $key => $value) { |
|
303 | if (isset($nonRewrittenKeys[$key])) { |
||
304 | continue; |
||
305 | } |
||
306 | $options['global'][$key] = $value; |
||
307 | unset($options[$key]); |
||
308 | } |
||
309 | if (empty($options['wrapperClass'])) { |
||
310 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
311 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection'; |
||
312 | } |
||
313 | if (empty($options['shardManagerClass'])) { |
||
314 | // Change the shard manager class only if the user does not already forced using a custom one. |
||
315 | $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager'; |
||
316 | } |
||
317 | } else { |
||
318 | unset($options['shards']); |
||
319 | } |
||
320 | |||
321 | return $options; |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * Loads the Doctrine ORM configuration. |
||
326 | * |
||
327 | * Usage example: |
||
328 | * |
||
329 | * <doctrine:orm id="mydm" connection="myconn" /> |
||
330 | * |
||
331 | * @param array $config An array of configuration settings |
||
332 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
333 | */ |
||
334 | protected function ormLoad(array $config, ContainerBuilder $container) |
||
335 | { |
||
336 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
337 | $loader->load('orm.xml'); |
||
338 | |||
339 | $entityManagers = []; |
||
340 | foreach (array_keys($config['entity_managers']) as $name) { |
||
341 | $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name); |
||
342 | } |
||
343 | $container->setParameter('doctrine.entity_managers', $entityManagers); |
||
344 | |||
345 | if (empty($config['default_entity_manager'])) { |
||
346 | $tmp = array_keys($entityManagers); |
||
347 | $config['default_entity_manager'] = reset($tmp); |
||
348 | } |
||
349 | $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']); |
||
350 | |||
351 | $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace']; |
||
352 | foreach ($options as $key) { |
||
353 | $container->setParameter('doctrine.orm.' . $key, $config[$key]); |
||
354 | } |
||
355 | |||
356 | $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager'])); |
||
357 | $container->getAlias('doctrine.orm.entity_manager')->setPublic(true); |
||
358 | |||
359 | $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles')); |
||
360 | |||
361 | foreach ($config['entity_managers'] as $name => $entityManager) { |
||
362 | $entityManager['name'] = $name; |
||
363 | $this->loadOrmEntityManager($entityManager, $container); |
||
364 | |||
365 | $this->loadPropertyInfoExtractor($name, $container); |
||
366 | $this->loadValidatorLoader($name, $container); |
||
367 | } |
||
368 | |||
369 | if ($config['resolve_target_entities']) { |
||
370 | $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity'); |
||
371 | foreach ($config['resolve_target_entities'] as $name => $implementation) { |
||
372 | $def->addMethodCall('addResolveTargetEntity', [ |
||
373 | $name, |
||
374 | $implementation, |
||
375 | [], |
||
376 | ]); |
||
377 | } |
||
378 | |||
379 | $def->addTag('doctrine.event_subscriber'); |
||
380 | } |
||
381 | |||
382 | $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class) |
||
383 | ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG); |
||
384 | |||
385 | $this->loadMessengerServices($container); |
||
386 | } |
||
387 | |||
388 | /** |
||
389 | * Loads a configured ORM entity manager. |
||
390 | * |
||
391 | * @param array $entityManager A configured ORM entity manager. |
||
392 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
393 | */ |
||
394 | protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container) |
||
524 | |||
525 | /** |
||
526 | * Loads an ORM entity managers bundle mapping information. |
||
527 | * |
||
528 | * There are two distinct configuration possibilities for mapping information: |
||
529 | * |
||
530 | * 1. Specify a bundle and optionally details where the entity and mapping information reside. |
||
531 | * 2. Specify an arbitrary mapping location. |
||
532 | * |
||
533 | * @param array $entityManager A configured ORM entity manager |
||
534 | * @param Definition $ormConfigDef A Definition instance |
||
535 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
536 | * |
||
537 | * @example |
||
538 | * |
||
539 | * doctrine.orm: |
||
540 | * mappings: |
||
541 | * MyBundle1: ~ |
||
542 | * MyBundle2: yml |
||
543 | * MyBundle3: { type: annotation, dir: Entities/ } |
||
544 | * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping } |
||
545 | * MyBundle5: |
||
546 | * type: yml |
||
547 | * dir: bundle-mappings/ |
||
548 | * alias: BundleAlias |
||
549 | * arbitrary_key: |
||
550 | * type: xml |
||
551 | * dir: %kernel.root_dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities |
||
552 | * prefix: DoctrineExtensions\Entities\ |
||
553 | * alias: DExt |
||
554 | * |
||
555 | * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but |
||
556 | * in the mappings key everything except alias is a required argument. |
||
557 | */ |
||
558 | protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) |
||
569 | |||
570 | /** |
||
571 | * Loads an ORM second level cache bundle mapping information. |
||
572 | * |
||
573 | * @param array $entityManager A configured ORM entity manager |
||
574 | * @param Definition $ormConfigDef A Definition instance |
||
575 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
576 | * |
||
577 | * @example |
||
578 | * entity_managers: |
||
579 | * default: |
||
580 | * second_level_cache: |
||
581 | * region_cache_driver: apc |
||
582 | * log_enabled: true |
||
583 | * regions: |
||
584 | * my_service_region: |
||
585 | * type: service |
||
586 | * service : "my_service_region" |
||
587 | * |
||
588 | * my_query_region: |
||
589 | * lifetime: 300 |
||
590 | * cache_driver: array |
||
591 | * type: filelock |
||
592 | * |
||
593 | * my_entity_region: |
||
594 | * lifetime: 600 |
||
595 | * cache_driver: |
||
596 | * type: apc |
||
597 | */ |
||
598 | protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) |
||
686 | |||
687 | /** |
||
688 | * {@inheritDoc} |
||
689 | */ |
||
690 | protected function getObjectManagerElementName($name) |
||
694 | |||
695 | protected function getMappingObjectDefaultName() |
||
699 | |||
700 | /** |
||
701 | * {@inheritDoc} |
||
702 | */ |
||
703 | protected function getMappingResourceConfigDirectory() |
||
707 | |||
708 | /** |
||
709 | * {@inheritDoc} |
||
710 | */ |
||
711 | protected function getMappingResourceExtension() |
||
715 | |||
716 | /** |
||
717 | * {@inheritDoc} |
||
718 | */ |
||
719 | protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container) |
||
720 | { |
||
721 | $serviceId = null; |
||
746 | |||
747 | /** |
||
748 | * Loads a configured entity managers cache drivers. |
||
749 | * |
||
750 | * @param array $entityManager A configured ORM entity manager. |
||
751 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
752 | */ |
||
753 | protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container) |
||
759 | |||
760 | /** |
||
761 | * Loads a property info extractor for each defined entity manager. |
||
762 | * |
||
763 | * @param string $entityManagerName |
||
764 | */ |
||
765 | private function loadPropertyInfoExtractor($entityManagerName, ContainerBuilder $container) |
||
786 | |||
787 | /** |
||
788 | * Loads a validator loader for each defined entity manager. |
||
789 | */ |
||
790 | private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container) : void |
||
801 | |||
802 | /** |
||
803 | * @param array $objectManager |
||
804 | * @param string $cacheName |
||
805 | */ |
||
806 | public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) |
||
810 | |||
811 | /** |
||
812 | * {@inheritDoc} |
||
813 | */ |
||
814 | public function getXsdValidationBasePath() |
||
818 | |||
819 | /** |
||
820 | * {@inheritDoc} |
||
821 | */ |
||
822 | public function getNamespace() |
||
826 | |||
827 | /** |
||
828 | * {@inheritDoc} |
||
829 | */ |
||
830 | public function getConfiguration(array $config, ContainerBuilder $container) |
||
834 | |||
835 | private function loadMessengerServices(ContainerBuilder $container) : void |
||
852 | |||
853 | private function createPoolCacheDefinition(ContainerBuilder $container, string $aliasId, string $poolName) : string |
||
867 | } |
||
868 |
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: