| Total Complexity | 65 |
| Total Lines | 260 |
| 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 = []) |
||
| 81 | } |
||
| 82 | |||
| 83 | /** |
||
| 84 | * {@inheritdoc} |
||
| 85 | * |
||
| 86 | * The context may contain serialization groups which helps defining joined entities that are readable. |
||
| 87 | */ |
||
| 88 | public function applyToItem(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, array $identifiers, string $operationName = null, array $context = []) |
||
| 89 | { |
||
| 90 | $this->apply(false, $queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context); |
||
| 91 | } |
||
| 92 | |||
| 93 | private function apply(bool $collection, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, ?string $resourceClass, ?string $operationName, array $context) |
||
| 94 | { |
||
| 95 | if (null === $resourceClass) { |
||
| 96 | throw new InvalidArgumentException('The "$resourceClass" parameter must not be null'); |
||
| 97 | } |
||
| 98 | |||
| 99 | $options = []; |
||
| 100 | if (null !== $operationName) { |
||
| 101 | $options[($collection ? 'collection' : 'item').'_operation_name'] = $operationName; |
||
| 102 | } |
||
| 103 | |||
| 104 | $forceEager = $this->shouldOperationForceEager($resourceClass, $options); |
||
| 105 | $fetchPartial = $this->shouldOperationFetchPartial($resourceClass, $options); |
||
| 106 | |||
| 107 | if (!isset($context['groups']) && !isset($context['attributes'])) { |
||
| 108 | $contextType = isset($context['api_denormalize']) ? 'denormalization_context' : 'normalization_context'; |
||
| 109 | $context += $this->getNormalizationContext($context['resource_class'] ?? $resourceClass, $contextType, $options); |
||
| 110 | } |
||
| 111 | |||
| 112 | if (empty($context[AbstractNormalizer::GROUPS]) && !isset($context[AbstractNormalizer::ATTRIBUTES])) { |
||
| 113 | return; |
||
| 114 | } |
||
| 115 | |||
| 116 | if (!empty($context[AbstractNormalizer::GROUPS])) { |
||
| 117 | $options['serializer_groups'] = (array) $context[AbstractNormalizer::GROUPS]; |
||
| 118 | } |
||
| 119 | |||
| 120 | $this->joinRelations($queryBuilder, $queryNameGenerator, $resourceClass, $forceEager, $fetchPartial, $queryBuilder->getRootAliases()[0], $options, $context); |
||
| 121 | } |
||
| 122 | |||
| 123 | /** |
||
| 124 | * Joins relations to eager load. |
||
| 125 | * |
||
| 126 | * @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 |
||
| 127 | * @param int $joinCount the number of joins |
||
| 128 | * @param int $currentDepth the current max depth |
||
| 129 | * |
||
| 130 | * @throws RuntimeException when the max number of joins has been reached |
||
| 131 | */ |
||
| 132 | 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) |
||
| 133 | { |
||
| 134 | if ($joinCount > $this->maxJoins) { |
||
| 135 | throw new RuntimeException('The total number of joined relations has exceeded the specified maximum. Raise the limit if necessary with the "api_platform.eager_loading.max_joins" configuration key (https://api-platform.com/docs/core/performance/#eager-loading), or limit the maximum serialization depth using the "enable_max_depth" option of the Symfony serializer (https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth).'); |
||
| 136 | } |
||
| 137 | |||
| 138 | $currentDepth = $currentDepth > 0 ? $currentDepth - 1 : $currentDepth; |
||
| 139 | $entityManager = $queryBuilder->getEntityManager(); |
||
| 140 | $classMetadata = $entityManager->getClassMetadata($resourceClass); |
||
| 141 | $attributesMetadata = $this->classMetadataFactory ? $this->classMetadataFactory->getMetadataFor($resourceClass)->getAttributesMetadata() : null; |
||
| 142 | |||
| 143 | foreach ($classMetadata->associationMappings as $association => $mapping) { |
||
| 144 | //Don't join if max depth is enabled and the current depth limit is reached |
||
| 145 | if (0 === $currentDepth && ($normalizationContext[AbstractObjectNormalizer::ENABLE_MAX_DEPTH] ?? false)) { |
||
| 146 | continue; |
||
| 147 | } |
||
| 148 | |||
| 149 | try { |
||
| 150 | $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $association, $options); |
||
| 151 | } catch (PropertyNotFoundException $propertyNotFoundException) { |
||
| 152 | //skip properties not found |
||
| 153 | continue; |
||
| 154 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
| 155 | //skip associations that are not resource classes |
||
| 156 | continue; |
||
| 157 | } |
||
| 158 | |||
| 159 | if ( |
||
| 160 | // Always skip extra lazy associations |
||
| 161 | ClassMetadataInfo::FETCH_EXTRA_LAZY === $mapping['fetch'] || |
||
| 162 | // We don't want to interfere with doctrine on this association |
||
| 163 | (false === $forceEager && ClassMetadataInfo::FETCH_EAGER !== $mapping['fetch']) |
||
| 164 | ) { |
||
| 165 | continue; |
||
| 166 | } |
||
| 167 | |||
| 168 | if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) { |
||
| 169 | if ($inAttributes = isset($normalizationContext[AbstractNormalizer::ATTRIBUTES][$association])) { |
||
| 170 | // prepare the child context |
||
| 171 | $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $normalizationContext[AbstractNormalizer::ATTRIBUTES][$association]; |
||
| 172 | } |
||
| 173 | } else { |
||
| 174 | $inAttributes = null; |
||
| 175 | } |
||
| 176 | |||
| 177 | if ( |
||
| 178 | (null === $fetchEager = $propertyMetadata->getAttribute('fetch_eager')) && |
||
| 179 | (null !== $fetchEager = $propertyMetadata->getAttribute('fetchEager')) |
||
| 180 | ) { |
||
| 181 | @trigger_error('The "fetchEager" attribute is deprecated since 2.3. Please use "fetch_eager" instead.', E_USER_DEPRECATED); |
||
| 182 | } |
||
| 183 | |||
| 184 | if (false === $fetchEager) { |
||
| 185 | continue; |
||
| 186 | } |
||
| 187 | |||
| 188 | $isNotReadableLink = false === $propertyMetadata->isReadableLink(); |
||
| 189 | if (null === $fetchEager && (false === $propertyMetadata->isReadable() || ((null === $inAttributes && $isNotReadableLink) || (false === $inAttributes)))) { |
||
| 190 | continue; |
||
| 191 | } |
||
| 192 | |||
| 193 | $isNullable = $mapping['joinColumns'][0]['nullable'] ?? true; |
||
| 194 | if (false !== $wasLeftJoin || true === $isNullable) { |
||
| 195 | $method = 'leftJoin'; |
||
| 196 | } else { |
||
| 197 | $method = 'innerJoin'; |
||
| 198 | } |
||
| 199 | |||
| 200 | $associationAlias = $queryNameGenerator->generateJoinAlias($association); |
||
| 201 | $queryBuilder->{$method}(sprintf('%s.%s', $parentAlias, $association), $associationAlias); |
||
| 202 | ++$joinCount; |
||
| 203 | |||
| 204 | if (true === $fetchPartial) { |
||
| 205 | try { |
||
| 206 | $this->addSelect($queryBuilder, $mapping['targetEntity'], $associationAlias, $options); |
||
| 207 | } catch (ResourceClassNotFoundException $resourceClassNotFoundException) { |
||
| 208 | continue; |
||
| 209 | } |
||
| 210 | } else { |
||
| 211 | $queryBuilder->addSelect($associationAlias); |
||
| 212 | } |
||
| 213 | |||
| 214 | // Avoid recursive joins |
||
| 215 | if ($mapping['targetEntity'] === $resourceClass) { |
||
| 216 | // Avoid joining the same association twice (see #1959) |
||
| 217 | if (!\in_array($associationAlias, $queryBuilder->getAllAliases(), true)) { |
||
| 218 | $queryBuilder->addSelect($associationAlias); |
||
| 219 | } |
||
| 220 | |||
| 221 | continue; |
||
| 222 | } |
||
| 223 | |||
| 224 | if (isset($attributesMetadata[$association])) { |
||
| 225 | $maxDepth = $attributesMetadata[$association]->getMaxDepth(); |
||
| 226 | |||
| 227 | // The current depth is the lowest max depth available in the ancestor tree. |
||
| 228 | if (null !== $maxDepth && (null === $currentDepth || $maxDepth < $currentDepth)) { |
||
| 229 | $currentDepth = $maxDepth; |
||
| 230 | } |
||
| 231 | } |
||
| 232 | |||
| 233 | $this->joinRelations($queryBuilder, $queryNameGenerator, $mapping['targetEntity'], $forceEager, $fetchPartial, $associationAlias, $options, $normalizationContext, 'leftJoin' === $method, $joinCount, $currentDepth); |
||
| 234 | } |
||
| 235 | } |
||
| 236 | |||
| 237 | private function addSelect(QueryBuilder $queryBuilder, string $entity, string $associationAlias, array $propertyMetadataOptions) |
||
| 238 | { |
||
| 239 | $select = []; |
||
| 240 | $entityManager = $queryBuilder->getEntityManager(); |
||
| 241 | $targetClassMetadata = $entityManager->getClassMetadata($entity); |
||
| 242 | if (!empty($targetClassMetadata->subClasses)) { |
||
| 243 | $queryBuilder->addSelect($associationAlias); |
||
| 244 | |||
| 245 | return; |
||
| 246 | } |
||
| 247 | |||
| 248 | foreach ($this->propertyNameCollectionFactory->create($entity) as $property) { |
||
| 249 | $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions); |
||
| 250 | |||
| 251 | if (true === $propertyMetadata->isIdentifier()) { |
||
| 252 | $select[] = $property; |
||
| 253 | continue; |
||
| 254 | } |
||
| 255 | |||
| 256 | // If it's an embedded property see below |
||
| 257 | if (!\array_key_exists($property, $targetClassMetadata->embeddedClasses)) { |
||
| 258 | //the field test allows to add methods to a Resource which do not reflect real database fields |
||
| 259 | if ($targetClassMetadata->hasField($property) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) { |
||
| 260 | $select[] = $property; |
||
| 261 | } |
||
| 262 | |||
| 263 | continue; |
||
| 264 | } |
||
| 265 | |||
| 266 | // It's an embedded property, select relevant subfields |
||
| 267 | foreach ($this->propertyNameCollectionFactory->create($targetClassMetadata->embeddedClasses[$property]['class']) as $embeddedProperty) { |
||
| 268 | $propertyMetadata = $this->propertyMetadataFactory->create($entity, $property, $propertyMetadataOptions); |
||
| 269 | $propertyName = "$property.$embeddedProperty"; |
||
| 270 | if ($targetClassMetadata->hasField($propertyName) && (true === $propertyMetadata->getAttribute('fetchable') || $propertyMetadata->isReadable())) { |
||
| 271 | $select[] = $propertyName; |
||
| 272 | } |
||
| 273 | } |
||
| 274 | } |
||
| 275 | |||
| 276 | $queryBuilder->addSelect(sprintf('partial %s.{%s}', $associationAlias, implode(',', $select))); |
||
| 277 | } |
||
| 278 | |||
| 279 | /** |
||
| 280 | * Gets the serializer context. |
||
| 281 | * |
||
| 282 | * @param string $contextType normalization_context or denormalization_context |
||
| 283 | * @param array $options represents the operation name so that groups are the one of the specific operation |
||
| 284 | */ |
||
| 285 | private function getNormalizationContext(string $resourceClass, string $contextType, array $options): array |
||
| 301 | } |
||
| 302 | } |
||
| 303 |