|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the API Platform project. |
| 5 | + * |
| 6 | + * (c) Kévin Dunglas <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +declare(strict_types=1); |
| 13 | + |
| 14 | +namespace ApiPlatform\JsonApi\Filter; |
| 15 | + |
| 16 | +use ApiPlatform\Metadata\Operation; |
| 17 | +use ApiPlatform\Metadata\Parameter; |
| 18 | +use ApiPlatform\State\ParameterProviderInterface; |
| 19 | +use Symfony\Component\Serializer\Normalizer\AbstractNormalizer; |
| 20 | + |
| 21 | +final readonly class SparseFieldsetParameterProvider implements ParameterProviderInterface |
| 22 | +{ |
| 23 | + public function provide(Parameter $parameter, array $parameters = [], array $context = []): ?Operation |
| 24 | + { |
| 25 | + if (!($operation = $context['operation'] ?? null)) { |
| 26 | + return null; |
| 27 | + } |
| 28 | + |
| 29 | + $allowedProperties = $parameter->getExtraProperties()['_properties'] ?? []; |
| 30 | + $value = $parameter->getValue(); |
| 31 | + $normalizationContext = $operation->getNormalizationContext(); |
| 32 | + |
| 33 | + if (!\is_array($value)) { |
| 34 | + return null; |
| 35 | + } |
| 36 | + |
| 37 | + $properties = []; |
| 38 | + $shortName = strtolower($operation->getShortName()); |
| 39 | + foreach ($value as $resource => $fields) { |
| 40 | + if (strtolower($resource) === $shortName) { |
| 41 | + $p = &$properties; |
| 42 | + } else { |
| 43 | + $properties[$resource] = []; |
| 44 | + $p = &$properties[$resource]; |
| 45 | + } |
| 46 | + |
| 47 | + foreach (explode(',', $fields) as $f) { |
| 48 | + if (\array_key_exists($f, $allowedProperties)) { |
| 49 | + $p[] = $f; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + if (isset($normalizationContext[AbstractNormalizer::ATTRIBUTES])) { |
| 55 | + $properties = array_merge_recursive((array) $normalizationContext[AbstractNormalizer::ATTRIBUTES], $properties); |
| 56 | + } |
| 57 | + |
| 58 | + $normalizationContext[AbstractNormalizer::ATTRIBUTES] = $properties; |
| 59 | + |
| 60 | + return $operation->withNormalizationContext($normalizationContext); |
| 61 | + } |
| 62 | +} |
0 commit comments