Total Complexity | 62 |
Total Lines | 253 |
Duplicated Lines | 0 % |
Changes | 0 |
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.
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 |
||
41 | final class EagerLoadingExtension implements ContextAwareQueryCollectionExtensionInterface, QueryItemExtensionInterface |
||
42 | { |
||
43 | use EagerLoadingTrait; |
||
|
|||
44 | |||
45 | private $propertyNameCollectionFactory; |
||
46 | private $propertyMetadataFactory; |
||
47 | private $classMetadataFactory; |
||
48 | private $maxJoins; |
||
49 | private $serializerContextBuilder; |
||
50 | private $requestStack; |
||
51 | |||
52 | /** |
||
53 | * @TODO move $fetchPartial after $forceEager (@soyuka) in 3.0 |
||
54 | */ |
||
55 | 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) |
||
56 | { |
||
57 | if (null !== $this->requestStack) { |
||
58 | @trigger_error(sprintf('Passing an instance of "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', RequestStack::class), E_USER_DEPRECATED); |
||
59 | } |
||
60 | if (null !== $this->serializerContextBuilder) { |
||
61 | @trigger_error(sprintf('Passing an instance of "%s" is deprecated since version 2.2 and will be removed in 3.0. Use the data provider\'s context instead.', SerializerContextBuilderInterface::class), E_USER_DEPRECATED); |
||
62 | } |
||
63 | |||
64 | $this->propertyNameCollectionFactory = $propertyNameCollectionFactory; |
||
65 | $this->propertyMetadataFactory = $propertyMetadataFactory; |
||
66 | $this->resourceMetadataFactory = $resourceMetadataFactory; |
||
67 | $this->classMetadataFactory = $classMetadataFactory; |
||
68 | $this->maxJoins = $maxJoins; |
||
69 | $this->forceEager = $forceEager; |
||
70 | $this->fetchPartial = $fetchPartial; |
||
71 | $this->serializerContextBuilder = $serializerContextBuilder; |
||
72 | $this->requestStack = $requestStack; |
||
73 | } |
||
74 | |||
75 | /** |
||
76 | * {@inheritdoc} |
||
77 | */ |
||
78 | public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context = []) |
||
79 | { |
||
80 | $this->apply(true, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context); |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * The context may contain serialization groups which helps defining joined entities that are readable. |
||
85 | */ |
||
86 | public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []) |
||
89 | } |
||
90 | |||
91 | private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass = null, string $operationName = null, array $context) |
||
115 | } |
||
116 | |||
117 | /** |
||
118 | * Joins relations to eager load. |
||
119 | * |
||
120 | * @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 |
||
121 | * @param int $joinCount the number of joins |
||
122 | * @param int $currentDepth the current max depth |
||
123 | * |
||
124 | * @throws RuntimeException when the max number of joins has been reached |
||
125 | */ |
||
126 | private function joinRelations(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, bool $forceEager, bool $fetchPartial, string $parentAlias, array $options = [], array $normalizationContext = [], bool $wasLeftJoin = false, int &$joinCount = 0, int $currentDepth = null) |
||
127 | { |
||
128 | if ($joinCount > $this->maxJoins) { |
||
129 | 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.'); |
||
130 | } |
||
131 | |||
132 | $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth; |
||
133 | $entityManager = $queryBuilder->getEntityManager(); |
||
134 | $classMetadata = $entityManager->getClassMetadata($resourceClass); |
||
135 | $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null; |
||
136 | |||
137 | if (!empty($normalizationContext[AbstractNormalizer::GROUPS])) { |
||
138 | $options['serializer_groups'] = $normalizationContext[AbstractNormalizer::GROUPS]; |
||
139 | } |
||
140 | |||
141 | foreach ($classMetadata->associationMappings as $association => $mapping) { |
||
142 | //Don't join if max depth is enabled and the current depth limit is reached |
||
143 | if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) { |
||
144 | continue; |
||
145 | } |
||
146 | |||
147 | try { |
||
148 | $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options); |
||
149 | } catch (PropertyNotFoundException $propertyNotFoundException) { |
||
150 | //skip properties not found |
||
151 | continue; |
||
152 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
153 | //skip associations that are not resource classes |
||
154 | continue; |
||
155 | } |
||
156 | |||
157 | if ( |
||
158 | // Always skip extra lazy associations |
||
159 | ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] || |
||
160 | // We don't want to interfere with doctrine on this association |
||
161 | (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) |
||
162 | ) { |
||
163 | continue; |
||
164 | } |
||
165 | |||
166 | if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) { |
||
167 | if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) { |
||
168 | // prepare the child context |
||
169 | $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association]; |
||
170 | } else { |
||
171 | unset($normalizationContext[AbstractNormalizer::ATTRIBUTES]); |
||
172 | } |
||
173 | } else { |
||
174 | $inAttributes = null; |
||
175 | } |
||
176 | |||
177 | if (false === $fetchEager = $propertyMetadata->getAttribute('fetchEager')) { |
||
178 | continue; |
||
179 | } |
||
180 | |||
181 | $isNotReadableLink = false === $propertyMetadata->isReadableLink(); |
||
182 | if (null === $fetchEager && (false === $propertyMetadata->isReadable() || ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes)))) { |
||
183 | continue; |
||
184 | } |
||
185 | |||
186 | $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true; |
||
187 | if (false !== $wasLeftJoin || true === $isNullable) { |
||
188 | $method = 'leftJoin'; |
||
189 | } else { |
||
190 | $method = 'innerJoin'; |
||
191 | } |
||
192 | |||
193 | $associationAlias = $queryNameGenerator->generateJoinAlias($association); |
||
194 | $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias); |
||
195 | ++$joinCount; |
||
196 | |||
197 | if (true === $fetchPartial) { |
||
198 | try { |
||
199 | $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options); |
||
200 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
201 | continue; |
||
202 | } |
||
203 | } else { |
||
204 | $queryBuilder->addSelect($associationAlias); |
||
205 | } |
||
206 | |||
207 | // Avoid recursive joins |
||
208 | if ($mapping['targetEntity'] === $resourceClass) { |
||
209 | // Avoid joining the same association twice (see #1959) |
||
210 | if (!\in_array($associationAlias, $queryBuilder->getAllAliases(), true)) { |
||
211 | $queryBuilder->addSelect($associationAlias); |
||
212 | } |
||
213 | |||
214 | continue; |
||
215 | } |
||
216 | |||
217 | if (isset($attributesMetadata[$association])) { |
||
218 | $maxDepth = $attributesMetadata[$association]->getMaxDepth(); |
||
219 | |||
220 | // The current depth is the lowest max depth available in the ancestor tree. |
||
221 | if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) { |
||
222 | $currentDepth = $maxDepth; |
||
223 | } |
||
224 | } |
||
225 | |||
226 | $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $normalizationContext, 'leftJoin' === $method, $joinCount, $currentDepth); |
||
227 | } |
||
228 | } |
||
229 | |||
230 | private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions) |
||
231 | { |
||
232 | $select = []; |
||
233 | $entityManager = $queryBuilder->getEntityManager(); |
||
234 | $targetClassMetadata = $entityManager->getClassMetadata($entity); |
||
235 | if (!empty($targetClassMetadata->subClasses)) { |
||
236 | $queryBuilder->addSelect($associationAlias); |
||
237 | |||
238 | return; |
||
239 | } |
||
240 | |||
241 | foreach ($this->propertyNameCollectionFactory->create($entity) as $property) { |
||
242 | $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions); |
||
243 | |||
244 | if (true === $propertyMetadata->isIdentifier()) { |
||
245 | $select[] = $property; |
||
246 | continue; |
||
247 | } |
||
248 | |||
249 | // If it's an embedded property see below |
||
250 | if (!array_key_exists($property, $targetClassMetadata->embeddedClasses)) { |
||
251 | //the field test allows to add methods to a Resource which do not reflect real database fields |
||
252 | if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) { |
||
253 | $select[] = $property; |
||
254 | } |
||
255 | |||
256 | continue; |
||
257 | } |
||
258 | |||
259 | // It's an embedded property, select relevent subfields |
||
260 | foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) { |
||
261 | $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions); |
||
262 | $propertyName = "$property.$embeddedProperty"; |
||
263 | if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) { |
||
264 | $select[] = $propertyName; |
||
265 | } |
||
266 | } |
||
267 | } |
||
268 | |||
269 | $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select))); |
||
270 | } |
||
271 | |||
272 | /** |
||
273 | * Gets the serializer context. |
||
274 | * |
||
275 | * @param string $contextType normalization_context or denormalization_context |
||
276 | * @param array $options represents the operation name so that groups are the one of the specific operation |
||
277 | */ |
||
278 | private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array |
||
294 | } |
||
295 | } |
||
296 |