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 EagerLoadingExtension 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 EagerLoadingExtension, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
38 | final class EagerLoadingExtension implements QueryCollectionExtensionInterface, QueryItemExtensionInterface |
||
39 | { |
||
40 | use EagerLoadingTrait; |
||
41 | |||
42 | private $propertyNameCollectionFactory; |
||
43 | private $propertyMetadataFactory; |
||
44 | private $classMetadataFactory; |
||
45 | private $maxJoins; |
||
46 | private $serializerContextBuilder; |
||
47 | private $requestStack; |
||
48 | |||
49 | /** |
||
50 | * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0 |
||
51 | */ |
||
52 | public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, ResourceMetadataFactoryInterface $resourceMetadataFactory, int $maxJoins = 30, bool $forceEager = true, RequestStack $requestStack = null, SerializerContextBuilderInterface $serializerContextBuilder = null, bool $fetchPartial = false, ClassMetadataFactoryInterface $classMetadataFactory = null) |
||
64 | |||
65 | /** |
||
66 | * {@inheritdoc} |
||
67 | */ |
||
68 | public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null) |
||
84 | |||
85 | /** |
||
86 | * {@inheritdoc} |
||
87 | * The context may contain serialization groups which helps defining joined entities that are readable. |
||
88 | */ |
||
89 | public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []) |
||
110 | |||
111 | /** |
||
112 | * Joins relations to eager load. |
||
113 | * |
||
114 | * @param QueryBuilder $queryBuilder |
||
115 | * @param QueryNameGeneratorInterface $queryNameGenerator |
||
116 | * @param string $resourceClass |
||
117 | * @param bool $forceEager |
||
118 | * @param string $parentAlias |
||
119 | * @param array $propertyMetadataOptions |
||
120 | * @param array $context |
||
121 | * @param bool $wasLeftJoin if the relation containing the new one had a left join, we have to force the new one to left join too |
||
122 | * @param int $joinCount the number of joins |
||
123 | * @param int $currentDepth the current max depth |
||
124 | * |
||
125 | * @throws RuntimeException when the max number of joins has been reached |
||
126 | */ |
||
127 | private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $propertyMetadataOptions = [], array $context = [], bool $wasLeftJoin = false, int &$joinCount = 0, int $currentDepth = null) |
||
128 | { |
||
129 | if ($joinCount > $this->maxJoins) { |
||
130 | throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary, or use the "max_depth" option of the Symfony serializer.'); |
||
131 | } |
||
132 | |||
133 | $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth; |
||
134 | $entityManager = $queryBuilder->getEntityManager(); |
||
135 | $classMetadata = $entityManager->getClassMetadata($resourceClass); |
||
136 | $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null; |
||
137 | |||
138 | foreach ($classMetadata->associationMappings as $association => $mapping) { |
||
139 | //Don't join if max depth is enabled and the current depth limit is reached |
||
140 | if (isset($context['enable_max_depth']) && 0 === $currentDepth) { |
||
141 | continue; |
||
142 | } |
||
143 | |||
144 | try { |
||
145 | $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $propertyMetadataOptions); |
||
146 | } catch (PropertyNotFoundException $propertyNotFoundException) { |
||
147 | //skip properties not found |
||
148 | continue; |
||
149 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
150 | //skip associations that are not resource classes |
||
151 | continue; |
||
152 | } |
||
153 | |||
154 | // We don't want to interfere with doctrine on this association |
||
155 | if (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) { |
||
156 | continue; |
||
157 | } |
||
158 | |||
159 | if (false === $propertyMetadata->isReadableLink() || false === $propertyMetadata->isReadable()) { |
||
160 | continue; |
||
161 | } |
||
162 | |||
163 | $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true; |
||
164 | if (false !== $wasLeftJoin || true === $isNullable) { |
||
165 | $method = 'leftJoin'; |
||
166 | } else { |
||
167 | $method = 'innerJoin'; |
||
168 | } |
||
169 | |||
170 | $associationAlias = $queryNameGenerator->generateJoinAlias($association); |
||
171 | $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias); |
||
172 | ++$joinCount; |
||
173 | |||
174 | if (true === $fetchPartial) { |
||
175 | try { |
||
176 | $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $propertyMetadataOptions); |
||
177 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
178 | continue; |
||
179 | } |
||
180 | } else { |
||
181 | $queryBuilder->addSelect($associationAlias); |
||
182 | } |
||
183 | |||
184 | // Avoid recursion |
||
185 | if ($mapping['targetEntity'] === $resourceClass) { |
||
186 | $queryBuilder->addSelect($associationAlias); |
||
187 | continue; |
||
188 | } |
||
189 | |||
190 | if (isset($attributesMetadata[$association])) { |
||
191 | $maxDepth = $attributesMetadata[$association]->getMaxDepth(); |
||
192 | |||
193 | // The current depth is the lowest max depth available in the ancestor tree. |
||
194 | if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) { |
||
195 | $currentDepth = $maxDepth; |
||
196 | } |
||
197 | } |
||
198 | |||
199 | $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $propertyMetadataOptions, $context, $method === 'leftJoin', $joinCount, $currentDepth); |
||
200 | } |
||
201 | } |
||
202 | |||
203 | private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions) |
||
238 | |||
239 | /** |
||
240 | * Gets serializer context. |
||
241 | * |
||
242 | * @param string $resourceClass |
||
243 | * @param string $contextType normalization_context or denormalization_context |
||
244 | * @param array $options represents the operation name so that groups are the one of the specific operation |
||
245 | * |
||
246 | * @return array |
||
247 | */ |
||
248 | private function getSerializerContext(string $resourceClass, string $contextType, array $options): array |
||
272 | |||
273 | /** |
||
274 | * Gets serializer groups if available, if not it returns the $options array. |
||
275 | * |
||
276 | * @param array $options represents the operation name so that groups are the one of the specific operation |
||
277 | * @param array $context |
||
278 | * |
||
279 | * @return array |
||
280 | */ |
||
281 | private function getSerializerGroups(array $options, array $context): array |
||
289 | } |
||
290 |
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.