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 |
||
31 | class DoctrineExtension extends AbstractDoctrineExtension |
||
32 | { |
||
33 | /** @var string */ |
||
34 | private $defaultConnection; |
||
35 | |||
36 | /** @var SymfonyBridgeAdapter */ |
||
37 | private $adapter; |
||
38 | |||
39 | public function __construct(SymfonyBridgeAdapter $adapter = null) |
||
40 | { |
||
41 | $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm'); |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * {@inheritDoc} |
||
46 | */ |
||
47 | public function load(array $configs, ContainerBuilder $container) |
||
48 | { |
||
49 | $configuration = $this->getConfiguration($configs, $container); |
||
50 | $config = $this->processConfiguration($configuration, $configs); |
||
|
|||
51 | |||
52 | $this->adapter->loadServicesConfiguration($container); |
||
53 | |||
54 | if (! empty($config['dbal'])) { |
||
55 | $this->dbalLoad($config['dbal'], $container); |
||
56 | } |
||
57 | |||
58 | if (empty($config['orm'])) { |
||
59 | return; |
||
60 | } |
||
61 | |||
62 | if (empty($config['dbal'])) { |
||
63 | throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.'); |
||
64 | } |
||
65 | |||
66 | if (! class_exists(Version::class)) { |
||
67 | throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.'); |
||
68 | } |
||
69 | |||
70 | $this->ormLoad($config['orm'], $container); |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * Loads the DBAL configuration. |
||
75 | * |
||
76 | * Usage example: |
||
77 | * |
||
78 | * <doctrine:dbal id="myconn" dbname="sfweb" user="root" /> |
||
79 | * |
||
80 | * @param array $config An array of configuration settings |
||
81 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
82 | */ |
||
83 | protected function dbalLoad(array $config, ContainerBuilder $container) |
||
84 | { |
||
85 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
86 | $loader->load('dbal.xml'); |
||
87 | |||
88 | if (empty($config['default_connection'])) { |
||
89 | $keys = array_keys($config['connections']); |
||
90 | $config['default_connection'] = reset($keys); |
||
91 | } |
||
92 | |||
93 | $this->defaultConnection = $config['default_connection']; |
||
94 | |||
95 | $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection)); |
||
96 | $container->getAlias('database_connection')->setPublic(true); |
||
97 | $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false)); |
||
98 | |||
99 | $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']); |
||
100 | |||
101 | $connections = []; |
||
102 | |||
103 | foreach (array_keys($config['connections']) as $name) { |
||
104 | $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name); |
||
105 | } |
||
106 | |||
107 | $container->setParameter('doctrine.connections', $connections); |
||
108 | $container->setParameter('doctrine.default_connection', $this->defaultConnection); |
||
109 | |||
110 | foreach ($config['connections'] as $name => $connection) { |
||
111 | $this->loadDbalConnection($name, $connection, $container); |
||
112 | } |
||
113 | } |
||
114 | |||
115 | /** |
||
116 | * Loads a configured DBAL connection. |
||
117 | * |
||
118 | * @param string $name The name of the connection |
||
119 | * @param array $connection A dbal connection configuration. |
||
120 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
121 | */ |
||
122 | protected function loadDbalConnection($name, array $connection, ContainerBuilder $container) |
||
123 | { |
||
124 | $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration')); |
||
125 | $logger = null; |
||
126 | if ($connection['logging']) { |
||
127 | $logger = new Reference('doctrine.dbal.logger'); |
||
128 | } |
||
129 | unset($connection['logging']); |
||
130 | if ($connection['profiling']) { |
||
131 | $profilingLoggerId = 'doctrine.dbal.logger.profiling.' . $name; |
||
132 | $container->setDefinition($profilingLoggerId, new ChildDefinition('doctrine.dbal.logger.profiling')); |
||
133 | $profilingLogger = new Reference($profilingLoggerId); |
||
134 | $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]); |
||
135 | |||
136 | if ($logger !== null) { |
||
137 | $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain'); |
||
138 | $chainLogger->addMethodCall('addLogger', [$profilingLogger]); |
||
139 | |||
140 | $loggerId = 'doctrine.dbal.logger.chain.' . $name; |
||
141 | $container->setDefinition($loggerId, $chainLogger); |
||
142 | $logger = new Reference($loggerId); |
||
143 | } else { |
||
144 | $logger = $profilingLogger; |
||
145 | } |
||
146 | } |
||
147 | unset($connection['profiling']); |
||
148 | |||
149 | if (isset($connection['auto_commit'])) { |
||
150 | $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]); |
||
151 | } |
||
152 | |||
153 | unset($connection['auto_commit']); |
||
154 | |||
155 | if (isset($connection['schema_filter']) && $connection['schema_filter']) { |
||
156 | $configuration->addMethodCall('setFilterSchemaAssetsExpression', [$connection['schema_filter']]); |
||
157 | } |
||
158 | |||
159 | unset($connection['schema_filter']); |
||
160 | |||
161 | if ($logger) { |
||
162 | $configuration->addMethodCall('setSQLLogger', [$logger]); |
||
163 | } |
||
164 | |||
165 | // event manager |
||
166 | $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager')); |
||
167 | |||
168 | // connection |
||
169 | $options = $this->getConnectionOptions($connection); |
||
170 | |||
171 | $def = $container |
||
172 | ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection')) |
||
173 | ->setPublic(true) |
||
174 | ->setArguments([ |
||
175 | $options, |
||
176 | new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)), |
||
177 | new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)), |
||
178 | $connection['mapping_types'], |
||
179 | ]); |
||
180 | |||
181 | // Set class in case "wrapper_class" option was used to assist IDEs |
||
182 | if (isset($options['wrapperClass'])) { |
||
183 | $def->setClass($options['wrapperClass']); |
||
184 | } |
||
185 | |||
186 | if (! empty($connection['use_savepoints'])) { |
||
187 | $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]); |
||
188 | } |
||
189 | |||
190 | // Create a shard_manager for this connection |
||
191 | if (! isset($options['shards'])) { |
||
192 | return; |
||
193 | } |
||
194 | |||
195 | $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]); |
||
196 | $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition); |
||
197 | } |
||
198 | |||
199 | protected function getConnectionOptions($connection) |
||
200 | { |
||
201 | $options = $connection; |
||
202 | |||
203 | if (isset($options['platform_service'])) { |
||
204 | $options['platform'] = new Reference($options['platform_service']); |
||
205 | unset($options['platform_service']); |
||
206 | } |
||
207 | unset($options['mapping_types']); |
||
208 | |||
209 | if (isset($options['shard_choser_service'])) { |
||
210 | $options['shard_choser'] = new Reference($options['shard_choser_service']); |
||
211 | unset($options['shard_choser_service']); |
||
212 | } |
||
213 | |||
214 | foreach ([ |
||
215 | 'options' => 'driverOptions', |
||
216 | 'driver_class' => 'driverClass', |
||
217 | 'wrapper_class' => 'wrapperClass', |
||
218 | 'keep_slave' => 'keepSlave', |
||
219 | 'shard_choser' => 'shardChoser', |
||
220 | 'shard_manager_class' => 'shardManagerClass', |
||
221 | 'server_version' => 'serverVersion', |
||
222 | 'default_table_options' => 'defaultTableOptions', |
||
223 | ] as $old => $new) { |
||
224 | if (! isset($options[$old])) { |
||
225 | continue; |
||
226 | } |
||
227 | |||
228 | $options[$new] = $options[$old]; |
||
229 | unset($options[$old]); |
||
230 | } |
||
231 | |||
232 | if (! empty($options['slaves']) && ! empty($options['shards'])) { |
||
233 | throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together'); |
||
234 | } |
||
235 | |||
236 | if (! empty($options['slaves'])) { |
||
237 | $nonRewrittenKeys = [ |
||
238 | 'driver' => true, |
||
239 | 'driverOptions' => true, |
||
240 | 'driverClass' => true, |
||
241 | 'wrapperClass' => true, |
||
242 | 'keepSlave' => true, |
||
243 | 'shardChoser' => true, |
||
244 | 'platform' => true, |
||
245 | 'slaves' => true, |
||
246 | 'master' => true, |
||
247 | 'shards' => true, |
||
248 | 'serverVersion' => true, |
||
249 | 'defaultTableOptions' => true, |
||
250 | // included by safety but should have been unset already |
||
251 | 'logging' => true, |
||
252 | 'profiling' => true, |
||
253 | 'mapping_types' => true, |
||
254 | 'platform_service' => true, |
||
255 | ]; |
||
256 | View Code Duplication | foreach ($options as $key => $value) { |
|
257 | if (isset($nonRewrittenKeys[$key])) { |
||
258 | continue; |
||
259 | } |
||
260 | $options['master'][$key] = $value; |
||
261 | unset($options[$key]); |
||
262 | } |
||
263 | if (empty($options['wrapperClass'])) { |
||
264 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
265 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection'; |
||
266 | } |
||
267 | } else { |
||
268 | unset($options['slaves']); |
||
269 | } |
||
270 | |||
271 | if (! empty($options['shards'])) { |
||
272 | $nonRewrittenKeys = [ |
||
273 | 'driver' => true, |
||
274 | 'driverOptions' => true, |
||
275 | 'driverClass' => true, |
||
276 | 'wrapperClass' => true, |
||
277 | 'keepSlave' => true, |
||
278 | 'shardChoser' => true, |
||
279 | 'platform' => true, |
||
280 | 'slaves' => true, |
||
281 | 'global' => true, |
||
282 | 'shards' => true, |
||
283 | 'serverVersion' => true, |
||
284 | 'defaultTableOptions' => true, |
||
285 | // included by safety but should have been unset already |
||
286 | 'logging' => true, |
||
287 | 'profiling' => true, |
||
288 | 'mapping_types' => true, |
||
289 | 'platform_service' => true, |
||
290 | ]; |
||
291 | View Code Duplication | foreach ($options as $key => $value) { |
|
292 | if (isset($nonRewrittenKeys[$key])) { |
||
293 | continue; |
||
294 | } |
||
295 | $options['global'][$key] = $value; |
||
296 | unset($options[$key]); |
||
297 | } |
||
298 | if (empty($options['wrapperClass'])) { |
||
299 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
300 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection'; |
||
301 | } |
||
302 | if (empty($options['shardManagerClass'])) { |
||
303 | // Change the shard manager class only if the user does not already forced using a custom one. |
||
304 | $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager'; |
||
305 | } |
||
306 | } else { |
||
307 | unset($options['shards']); |
||
308 | } |
||
309 | |||
310 | return $options; |
||
311 | } |
||
312 | |||
313 | /** |
||
314 | * Loads the Doctrine ORM configuration. |
||
315 | * |
||
316 | * Usage example: |
||
317 | * |
||
318 | * <doctrine:orm id="mydm" connection="myconn" /> |
||
319 | * |
||
320 | * @param array $config An array of configuration settings |
||
321 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
322 | */ |
||
323 | protected function ormLoad(array $config, ContainerBuilder $container) |
||
324 | { |
||
325 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
326 | $loader->load('orm.xml'); |
||
327 | |||
328 | $entityManagers = []; |
||
329 | foreach (array_keys($config['entity_managers']) as $name) { |
||
330 | $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name); |
||
331 | } |
||
332 | $container->setParameter('doctrine.entity_managers', $entityManagers); |
||
333 | |||
334 | if (empty($config['default_entity_manager'])) { |
||
335 | $tmp = array_keys($entityManagers); |
||
336 | $config['default_entity_manager'] = reset($tmp); |
||
337 | } |
||
338 | $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']); |
||
339 | |||
340 | $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace']; |
||
341 | foreach ($options as $key) { |
||
342 | $container->setParameter('doctrine.orm.' . $key, $config[$key]); |
||
343 | } |
||
344 | |||
345 | $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager'])); |
||
346 | $container->getAlias('doctrine.orm.entity_manager')->setPublic(true); |
||
347 | |||
348 | $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles')); |
||
349 | |||
350 | foreach ($config['entity_managers'] as $name => $entityManager) { |
||
351 | $entityManager['name'] = $name; |
||
352 | $this->loadOrmEntityManager($entityManager, $container); |
||
353 | |||
354 | $this->loadPropertyInfoExtractor($name, $container); |
||
355 | $this->loadValidatorLoader($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 | $this->loadMessengerServices($container); |
||
375 | } |
||
376 | |||
377 | /** |
||
378 | * Loads a configured ORM entity manager. |
||
379 | * |
||
380 | * @param array $entityManager A configured ORM entity manager. |
||
381 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
382 | */ |
||
383 | protected function loadOrmEntityManager(array $entityManager, ContainerBuilder $container) |
||
513 | |||
514 | /** |
||
515 | * Loads an ORM entity managers bundle mapping information. |
||
516 | * |
||
517 | * There are two distinct configuration possibilities for mapping information: |
||
518 | * |
||
519 | * 1. Specify a bundle and optionally details where the entity and mapping information reside. |
||
520 | * 2. Specify an arbitrary mapping location. |
||
521 | * |
||
522 | * @param array $entityManager A configured ORM entity manager |
||
523 | * @param Definition $ormConfigDef A Definition instance |
||
524 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
525 | * |
||
526 | * @example |
||
527 | * |
||
528 | * doctrine.orm: |
||
529 | * mappings: |
||
530 | * MyBundle1: ~ |
||
531 | * MyBundle2: yml |
||
532 | * MyBundle3: { type: annotation, dir: Entities/ } |
||
533 | * MyBundle4: { type: xml, dir: Resources/config/doctrine/mapping } |
||
534 | * MyBundle5: |
||
535 | * type: yml |
||
536 | * dir: bundle-mappings/ |
||
537 | * alias: BundleAlias |
||
538 | * arbitrary_key: |
||
539 | * type: xml |
||
540 | * dir: %kernel.root_dir%/../src/vendor/DoctrineExtensions/lib/DoctrineExtensions/Entities |
||
541 | * prefix: DoctrineExtensions\Entities\ |
||
542 | * alias: DExt |
||
543 | * |
||
544 | * In the case of bundles everything is really optional (which leads to autodetection for this bundle) but |
||
545 | * in the mappings key everything except alias is a required argument. |
||
546 | */ |
||
547 | protected function loadOrmEntityManagerMappingInformation(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) |
||
558 | |||
559 | /** |
||
560 | * Loads an ORM second level cache bundle mapping information. |
||
561 | * |
||
562 | * @param array $entityManager A configured ORM entity manager |
||
563 | * @param Definition $ormConfigDef A Definition instance |
||
564 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
565 | * |
||
566 | * @example |
||
567 | * entity_managers: |
||
568 | * default: |
||
569 | * second_level_cache: |
||
570 | * region_cache_driver: apc |
||
571 | * log_enabled: true |
||
572 | * regions: |
||
573 | * my_service_region: |
||
574 | * type: service |
||
575 | * service : "my_service_region" |
||
576 | * |
||
577 | * my_query_region: |
||
578 | * lifetime: 300 |
||
579 | * cache_driver: array |
||
580 | * type: filelock |
||
581 | * |
||
582 | * my_entity_region: |
||
583 | * lifetime: 600 |
||
584 | * cache_driver: |
||
585 | * type: apc |
||
586 | */ |
||
587 | protected function loadOrmSecondLevelCache(array $entityManager, Definition $ormConfigDef, ContainerBuilder $container) |
||
675 | |||
676 | /** |
||
677 | * {@inheritDoc} |
||
678 | */ |
||
679 | protected function getObjectManagerElementName($name) |
||
683 | |||
684 | protected function getMappingObjectDefaultName() |
||
688 | |||
689 | /** |
||
690 | * {@inheritDoc} |
||
691 | */ |
||
692 | protected function getMappingResourceConfigDirectory() |
||
696 | |||
697 | /** |
||
698 | * {@inheritDoc} |
||
699 | */ |
||
700 | protected function getMappingResourceExtension() |
||
704 | |||
705 | /** |
||
706 | * {@inheritDoc} |
||
707 | */ |
||
708 | protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container) |
||
721 | |||
722 | /** |
||
723 | * Loads a configured entity managers cache drivers. |
||
724 | * |
||
725 | * @param array $entityManager A configured ORM entity manager. |
||
726 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
727 | */ |
||
728 | protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container) |
||
734 | |||
735 | /** |
||
736 | * Loads a property info extractor for each defined entity manager. |
||
737 | * |
||
738 | * @param string $entityManagerName |
||
739 | */ |
||
740 | private function loadPropertyInfoExtractor($entityManagerName, ContainerBuilder $container) |
||
761 | |||
762 | /** |
||
763 | * Loads a validator loader for each defined entity manager. |
||
764 | */ |
||
765 | private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container) : void |
||
766 | { |
||
767 | if (! interface_exists(LoaderInterface::class) || ! class_exists(DoctrineLoader::class)) { |
||
776 | |||
777 | /** |
||
778 | * @param array $objectManager |
||
779 | * @param string $cacheName |
||
780 | */ |
||
781 | public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) |
||
785 | |||
786 | /** |
||
787 | * {@inheritDoc} |
||
788 | */ |
||
789 | public function getXsdValidationBasePath() |
||
793 | |||
794 | /** |
||
795 | * {@inheritDoc} |
||
796 | */ |
||
797 | public function getNamespace() |
||
801 | |||
802 | /** |
||
803 | * {@inheritDoc} |
||
804 | */ |
||
805 | public function getConfiguration(array $config, ContainerBuilder $container) |
||
809 | |||
810 | private function loadMessengerServices(ContainerBuilder $container) : void |
||
827 | } |
||
828 |
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: