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 |
||
38 | class DoctrineExtension extends AbstractDoctrineExtension |
||
39 | { |
||
40 | /** @var string */ |
||
41 | private $defaultConnection; |
||
42 | |||
43 | /** @var SymfonyBridgeAdapter */ |
||
44 | private $adapter; |
||
45 | |||
46 | public function __construct(SymfonyBridgeAdapter $adapter = null) |
||
47 | { |
||
48 | $this->adapter = $adapter ?: new SymfonyBridgeAdapter(new CacheProviderLoader(), 'doctrine.orm', 'orm'); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * {@inheritDoc} |
||
53 | */ |
||
54 | public function load(array $configs, ContainerBuilder $container) |
||
55 | { |
||
56 | $configuration = $this->getConfiguration($configs, $container); |
||
57 | $config = $this->processConfiguration($configuration, $configs); |
||
|
|||
58 | |||
59 | $this->adapter->loadServicesConfiguration($container); |
||
60 | |||
61 | if (! empty($config['dbal'])) { |
||
62 | $this->dbalLoad($config['dbal'], $container); |
||
63 | } |
||
64 | |||
65 | if (empty($config['orm'])) { |
||
66 | return; |
||
67 | } |
||
68 | |||
69 | if (empty($config['dbal'])) { |
||
70 | throw new LogicException('Configuring the ORM layer requires to configure the DBAL layer as well.'); |
||
71 | } |
||
72 | |||
73 | if (! class_exists(Version::class)) { |
||
74 | throw new LogicException('To configure the ORM layer, you must first install the doctrine/orm package.'); |
||
75 | } |
||
76 | |||
77 | $this->ormLoad($config['orm'], $container); |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Loads the DBAL configuration. |
||
82 | * |
||
83 | * Usage example: |
||
84 | * |
||
85 | * <doctrine:dbal id="myconn" dbname="sfweb" user="root" /> |
||
86 | * |
||
87 | * @param array $config An array of configuration settings |
||
88 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
89 | */ |
||
90 | protected function dbalLoad(array $config, ContainerBuilder $container) |
||
91 | { |
||
92 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
93 | $loader->load('dbal.xml'); |
||
94 | |||
95 | if (empty($config['default_connection'])) { |
||
96 | $keys = array_keys($config['connections']); |
||
97 | $config['default_connection'] = reset($keys); |
||
98 | } |
||
99 | |||
100 | $this->defaultConnection = $config['default_connection']; |
||
101 | |||
102 | $container->setAlias('database_connection', sprintf('doctrine.dbal.%s_connection', $this->defaultConnection)); |
||
103 | $container->getAlias('database_connection')->setPublic(true); |
||
104 | $container->setAlias('doctrine.dbal.event_manager', new Alias(sprintf('doctrine.dbal.%s_connection.event_manager', $this->defaultConnection), false)); |
||
105 | |||
106 | $container->setParameter('doctrine.dbal.connection_factory.types', $config['types']); |
||
107 | |||
108 | $connections = []; |
||
109 | |||
110 | foreach (array_keys($config['connections']) as $name) { |
||
111 | $connections[$name] = sprintf('doctrine.dbal.%s_connection', $name); |
||
112 | } |
||
113 | |||
114 | $container->setParameter('doctrine.connections', $connections); |
||
115 | $container->setParameter('doctrine.default_connection', $this->defaultConnection); |
||
116 | |||
117 | foreach ($config['connections'] as $name => $connection) { |
||
118 | $this->loadDbalConnection($name, $connection, $container); |
||
119 | } |
||
120 | } |
||
121 | |||
122 | /** |
||
123 | * Loads a configured DBAL connection. |
||
124 | * |
||
125 | * @param string $name The name of the connection |
||
126 | * @param array $connection A dbal connection configuration. |
||
127 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
128 | */ |
||
129 | protected function loadDbalConnection($name, array $connection, ContainerBuilder $container) |
||
130 | { |
||
131 | $configuration = $container->setDefinition(sprintf('doctrine.dbal.%s_connection.configuration', $name), new ChildDefinition('doctrine.dbal.connection.configuration')); |
||
132 | $logger = null; |
||
133 | if ($connection['logging']) { |
||
134 | $logger = new Reference('doctrine.dbal.logger'); |
||
135 | } |
||
136 | unset($connection['logging']); |
||
137 | if ($connection['profiling']) { |
||
138 | $profilingLoggerId = 'doctrine.dbal.logger.profiling.' . $name; |
||
139 | $container->setDefinition($profilingLoggerId, new ChildDefinition('doctrine.dbal.logger.profiling')); |
||
140 | $profilingLogger = new Reference($profilingLoggerId); |
||
141 | $container->getDefinition('data_collector.doctrine')->addMethodCall('addLogger', [$name, $profilingLogger]); |
||
142 | |||
143 | if ($logger !== null) { |
||
144 | $chainLogger = new ChildDefinition('doctrine.dbal.logger.chain'); |
||
145 | $chainLogger->addMethodCall('addLogger', [$profilingLogger]); |
||
146 | |||
147 | $loggerId = 'doctrine.dbal.logger.chain.' . $name; |
||
148 | $container->setDefinition($loggerId, $chainLogger); |
||
149 | $logger = new Reference($loggerId); |
||
150 | } else { |
||
151 | $logger = $profilingLogger; |
||
152 | } |
||
153 | } |
||
154 | unset($connection['profiling']); |
||
155 | |||
156 | if (isset($connection['auto_commit'])) { |
||
157 | $configuration->addMethodCall('setAutoCommit', [$connection['auto_commit']]); |
||
158 | } |
||
159 | |||
160 | unset($connection['auto_commit']); |
||
161 | |||
162 | if (isset($connection['schema_filter']) && $connection['schema_filter']) { |
||
163 | if (method_exists(\Doctrine\DBAL\Configuration::class, 'setSchemaAssetsFilter')) { |
||
164 | $definition = new Definition(RegexSchemaAssetFilter::class, [$connection['schema_filter']]); |
||
165 | $definition->addTag('doctrine.dbal.schema_filter', ['connection' => $name]); |
||
166 | $container->setDefinition(sprintf('doctrine.dbal.%s_regex_schema_filter', $name), $definition); |
||
167 | } else { |
||
168 | // backwards compatibility with dbal < 2.9 |
||
169 | $configuration->addMethodCall('setFilterSchemaAssetsExpression', [$connection['schema_filter']]); |
||
170 | } |
||
171 | } |
||
172 | |||
173 | unset($connection['schema_filter']); |
||
174 | |||
175 | if ($logger) { |
||
176 | $configuration->addMethodCall('setSQLLogger', [$logger]); |
||
177 | } |
||
178 | |||
179 | // event manager |
||
180 | $container->setDefinition(sprintf('doctrine.dbal.%s_connection.event_manager', $name), new ChildDefinition('doctrine.dbal.connection.event_manager')); |
||
181 | |||
182 | // connection |
||
183 | $options = $this->getConnectionOptions($connection); |
||
184 | |||
185 | $def = $container |
||
186 | ->setDefinition(sprintf('doctrine.dbal.%s_connection', $name), new ChildDefinition('doctrine.dbal.connection')) |
||
187 | ->setPublic(true) |
||
188 | ->setArguments([ |
||
189 | $options, |
||
190 | new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $name)), |
||
191 | new Reference(sprintf('doctrine.dbal.%s_connection.event_manager', $name)), |
||
192 | $connection['mapping_types'], |
||
193 | ]); |
||
194 | |||
195 | // Set class in case "wrapper_class" option was used to assist IDEs |
||
196 | if (isset($options['wrapperClass'])) { |
||
197 | $def->setClass($options['wrapperClass']); |
||
198 | } |
||
199 | |||
200 | if (! empty($connection['use_savepoints'])) { |
||
201 | $def->addMethodCall('setNestTransactionsWithSavepoints', [$connection['use_savepoints']]); |
||
202 | } |
||
203 | |||
204 | // Create a shard_manager for this connection |
||
205 | if (! isset($options['shards'])) { |
||
206 | return; |
||
207 | } |
||
208 | |||
209 | $shardManagerDefinition = new Definition($options['shardManagerClass'], [new Reference(sprintf('doctrine.dbal.%s_connection', $name))]); |
||
210 | $container->setDefinition(sprintf('doctrine.dbal.%s_shard_manager', $name), $shardManagerDefinition); |
||
211 | } |
||
212 | |||
213 | protected function getConnectionOptions($connection) |
||
214 | { |
||
215 | $options = $connection; |
||
216 | |||
217 | if (isset($options['platform_service'])) { |
||
218 | $options['platform'] = new Reference($options['platform_service']); |
||
219 | unset($options['platform_service']); |
||
220 | } |
||
221 | unset($options['mapping_types']); |
||
222 | |||
223 | if (isset($options['shard_choser_service'])) { |
||
224 | $options['shard_choser'] = new Reference($options['shard_choser_service']); |
||
225 | unset($options['shard_choser_service']); |
||
226 | } |
||
227 | |||
228 | foreach ([ |
||
229 | 'options' => 'driverOptions', |
||
230 | 'driver_class' => 'driverClass', |
||
231 | 'wrapper_class' => 'wrapperClass', |
||
232 | 'keep_slave' => 'keepSlave', |
||
233 | 'shard_choser' => 'shardChoser', |
||
234 | 'shard_manager_class' => 'shardManagerClass', |
||
235 | 'server_version' => 'serverVersion', |
||
236 | 'default_table_options' => 'defaultTableOptions', |
||
237 | ] as $old => $new) { |
||
238 | if (! isset($options[$old])) { |
||
239 | continue; |
||
240 | } |
||
241 | |||
242 | $options[$new] = $options[$old]; |
||
243 | unset($options[$old]); |
||
244 | } |
||
245 | |||
246 | if (! empty($options['slaves']) && ! empty($options['shards'])) { |
||
247 | throw new InvalidArgumentException('Sharding and master-slave connection cannot be used together'); |
||
248 | } |
||
249 | |||
250 | if (! empty($options['slaves'])) { |
||
251 | $nonRewrittenKeys = [ |
||
252 | 'driver' => true, |
||
253 | 'driverOptions' => true, |
||
254 | 'driverClass' => true, |
||
255 | 'wrapperClass' => true, |
||
256 | 'keepSlave' => true, |
||
257 | 'shardChoser' => true, |
||
258 | 'platform' => true, |
||
259 | 'slaves' => true, |
||
260 | 'master' => true, |
||
261 | 'shards' => true, |
||
262 | 'serverVersion' => true, |
||
263 | 'defaultTableOptions' => true, |
||
264 | // included by safety but should have been unset already |
||
265 | 'logging' => true, |
||
266 | 'profiling' => true, |
||
267 | 'mapping_types' => true, |
||
268 | 'platform_service' => true, |
||
269 | ]; |
||
270 | View Code Duplication | foreach ($options as $key => $value) { |
|
271 | if (isset($nonRewrittenKeys[$key])) { |
||
272 | continue; |
||
273 | } |
||
274 | $options['master'][$key] = $value; |
||
275 | unset($options[$key]); |
||
276 | } |
||
277 | if (empty($options['wrapperClass'])) { |
||
278 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
279 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Connections\\MasterSlaveConnection'; |
||
280 | } |
||
281 | } else { |
||
282 | unset($options['slaves']); |
||
283 | } |
||
284 | |||
285 | if (! empty($options['shards'])) { |
||
286 | $nonRewrittenKeys = [ |
||
287 | 'driver' => true, |
||
288 | 'driverOptions' => true, |
||
289 | 'driverClass' => true, |
||
290 | 'wrapperClass' => true, |
||
291 | 'keepSlave' => true, |
||
292 | 'shardChoser' => true, |
||
293 | 'platform' => true, |
||
294 | 'slaves' => true, |
||
295 | 'global' => true, |
||
296 | 'shards' => true, |
||
297 | 'serverVersion' => true, |
||
298 | 'defaultTableOptions' => true, |
||
299 | // included by safety but should have been unset already |
||
300 | 'logging' => true, |
||
301 | 'profiling' => true, |
||
302 | 'mapping_types' => true, |
||
303 | 'platform_service' => true, |
||
304 | ]; |
||
305 | View Code Duplication | foreach ($options as $key => $value) { |
|
306 | if (isset($nonRewrittenKeys[$key])) { |
||
307 | continue; |
||
308 | } |
||
309 | $options['global'][$key] = $value; |
||
310 | unset($options[$key]); |
||
311 | } |
||
312 | if (empty($options['wrapperClass'])) { |
||
313 | // Change the wrapper class only if the user does not already forced using a custom one. |
||
314 | $options['wrapperClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardConnection'; |
||
315 | } |
||
316 | if (empty($options['shardManagerClass'])) { |
||
317 | // Change the shard manager class only if the user does not already forced using a custom one. |
||
318 | $options['shardManagerClass'] = 'Doctrine\\DBAL\\Sharding\\PoolingShardManager'; |
||
319 | } |
||
320 | } else { |
||
321 | unset($options['shards']); |
||
322 | } |
||
323 | |||
324 | return $options; |
||
325 | } |
||
326 | |||
327 | /** |
||
328 | * Loads the Doctrine ORM configuration. |
||
329 | * |
||
330 | * Usage example: |
||
331 | * |
||
332 | * <doctrine:orm id="mydm" connection="myconn" /> |
||
333 | * |
||
334 | * @param array $config An array of configuration settings |
||
335 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
336 | */ |
||
337 | protected function ormLoad(array $config, ContainerBuilder $container) |
||
338 | { |
||
339 | $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); |
||
340 | $loader->load('orm.xml'); |
||
341 | |||
342 | $entityManagers = []; |
||
343 | foreach (array_keys($config['entity_managers']) as $name) { |
||
344 | $entityManagers[$name] = sprintf('doctrine.orm.%s_entity_manager', $name); |
||
345 | } |
||
346 | $container->setParameter('doctrine.entity_managers', $entityManagers); |
||
347 | |||
348 | if (empty($config['default_entity_manager'])) { |
||
349 | $tmp = array_keys($entityManagers); |
||
350 | $config['default_entity_manager'] = reset($tmp); |
||
351 | } |
||
352 | $container->setParameter('doctrine.default_entity_manager', $config['default_entity_manager']); |
||
353 | |||
354 | $options = ['auto_generate_proxy_classes', 'proxy_dir', 'proxy_namespace']; |
||
355 | foreach ($options as $key) { |
||
356 | $container->setParameter('doctrine.orm.' . $key, $config[$key]); |
||
357 | } |
||
358 | |||
359 | $container->setAlias('doctrine.orm.entity_manager', sprintf('doctrine.orm.%s_entity_manager', $config['default_entity_manager'])); |
||
360 | $container->getAlias('doctrine.orm.entity_manager')->setPublic(true); |
||
361 | |||
362 | $config['entity_managers'] = $this->fixManagersAutoMappings($config['entity_managers'], $container->getParameter('kernel.bundles')); |
||
363 | |||
364 | $loadPropertyInfoExtractor = interface_exists(PropertyInfoExtractorInterface::class) |
||
365 | && class_exists(DoctrineExtractor::class); |
||
366 | |||
367 | foreach ($config['entity_managers'] as $name => $entityManager) { |
||
368 | $entityManager['name'] = $name; |
||
369 | $this->loadOrmEntityManager($entityManager, $container); |
||
370 | |||
371 | if ($loadPropertyInfoExtractor) { |
||
372 | $this->loadPropertyInfoExtractor($name, $container); |
||
373 | } |
||
374 | |||
375 | $this->loadValidatorLoader($name, $container); |
||
376 | } |
||
377 | |||
378 | if ($config['resolve_target_entities']) { |
||
379 | $def = $container->findDefinition('doctrine.orm.listeners.resolve_target_entity'); |
||
380 | foreach ($config['resolve_target_entities'] as $name => $implementation) { |
||
381 | $def->addMethodCall('addResolveTargetEntity', [ |
||
382 | $name, |
||
383 | $implementation, |
||
384 | [], |
||
385 | ]); |
||
386 | } |
||
387 | |||
388 | $def->addTag('doctrine.event_subscriber'); |
||
389 | } |
||
390 | |||
391 | $container->registerForAutoconfiguration(ServiceEntityRepositoryInterface::class) |
||
392 | ->addTag(ServiceRepositoryCompilerPass::REPOSITORY_SERVICE_TAG); |
||
393 | |||
394 | $this->loadMessengerServices($container); |
||
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) |
||
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) |
||
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) |
||
695 | |||
696 | /** |
||
697 | * {@inheritDoc} |
||
698 | */ |
||
699 | protected function getObjectManagerElementName($name) |
||
703 | |||
704 | protected function getMappingObjectDefaultName() |
||
708 | |||
709 | /** |
||
710 | * {@inheritDoc} |
||
711 | */ |
||
712 | protected function getMappingResourceConfigDirectory() |
||
716 | |||
717 | /** |
||
718 | * {@inheritDoc} |
||
719 | */ |
||
720 | protected function getMappingResourceExtension() |
||
724 | |||
725 | /** |
||
726 | * {@inheritDoc} |
||
727 | */ |
||
728 | protected function loadCacheDriver($driverName, $entityManagerName, array $driverMap, ContainerBuilder $container) |
||
729 | { |
||
730 | $serviceId = null; |
||
755 | |||
756 | /** |
||
757 | * Loads a configured entity managers cache drivers. |
||
758 | * |
||
759 | * @param array $entityManager A configured ORM entity manager. |
||
760 | * @param ContainerBuilder $container A ContainerBuilder instance |
||
761 | */ |
||
762 | protected function loadOrmCacheDrivers(array $entityManager, ContainerBuilder $container) |
||
768 | |||
769 | /** |
||
770 | * Loads a property info extractor for each defined entity manager. |
||
771 | * |
||
772 | * @param string $entityManagerName |
||
773 | */ |
||
774 | private function loadPropertyInfoExtractor($entityManagerName, ContainerBuilder $container) |
||
795 | |||
796 | /** |
||
797 | * Loads a validator loader for each defined entity manager. |
||
798 | */ |
||
799 | private function loadValidatorLoader(string $entityManagerName, ContainerBuilder $container) : void |
||
810 | |||
811 | /** |
||
812 | * @param array $objectManager |
||
813 | * @param string $cacheName |
||
814 | */ |
||
815 | public function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) |
||
819 | |||
820 | /** |
||
821 | * {@inheritDoc} |
||
822 | */ |
||
823 | public function getXsdValidationBasePath() |
||
827 | |||
828 | /** |
||
829 | * {@inheritDoc} |
||
830 | */ |
||
831 | public function getNamespace() |
||
835 | |||
836 | /** |
||
837 | * {@inheritDoc} |
||
838 | */ |
||
839 | public function getConfiguration(array $config, ContainerBuilder $container) |
||
843 | |||
844 | private function loadMessengerServices(ContainerBuilder $container) : void |
||
869 | |||
870 | private function createPoolCacheDefinition(ContainerBuilder $container, string $aliasId, string $poolName) : string |
||
884 | } |
||
885 |
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: