• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 17054099799

18 Aug 2025 10:28PM UTC coverage: 22.386% (-0.2%) from 22.612%
17054099799

Pull #7150

github

web-flow
Merge 973c71211 into 2d501b315
Pull Request #7150: fix: array shape in ProviderInterface

11062 of 49414 relevant lines covered (22.39%)

11.75 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

32.43
/src/Serializer/ItemNormalizer.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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\Serializer;
15

16
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
17
use ApiPlatform\Metadata\HttpOperation;
18
use ApiPlatform\Metadata\IriConverterInterface;
19
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
22
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
23
use ApiPlatform\Metadata\ResourceClassResolverInterface;
24
use ApiPlatform\Metadata\UrlGeneratorInterface;
25
use Psr\Log\LoggerInterface;
26
use Psr\Log\NullLogger;
27
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
28
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
29
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
30
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
31

32
/**
33
 * Generic item normalizer.
34
 *
35
 * @author Kévin Dunglas <dunglas@gmail.com>
36
 */
37
class ItemNormalizer extends AbstractItemNormalizer
38
{
39
    private readonly LoggerInterface $logger;
40

41
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null)
42
    {
43
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector);
297✔
44

45
        $this->logger = $logger ?: new NullLogger();
297✔
46
    }
47

48
    /**
49
     * {@inheritdoc}
50
     *
51
     * @throws NotNormalizableValueException
52
     */
53
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
54
    {
55
        // Avoid issues with proxies if we populated the object
56
        if (isset($data['id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
8✔
57
            if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
×
58
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
×
59
            }
60

61
            if (isset($context['resource_class'])) {
×
62
                $this->updateObjectToPopulate($data, $context);
×
63
            } else {
64
                // See https://github.com/api-platform/core/pull/2326 to understand this message.
65
                $this->logger->warning('The "resource_class" key is missing from the context.', [
×
66
                    'context' => $context,
×
67
                ]);
×
68
            }
69
        }
70

71
        // See https://github.com/api-platform/core/pull/7270 - id may be an allowed attribute due to being added in the
72
        // overridden getAllowedAttributes below, in order to allow updating a nested item via ID. But in this case it
73
        // may not "really" be an allowed attribute, ie we don't want to actually use it in denormalization. In this
74
        // scenario it will not be present in parent::getAllowedAttributes
75
        if (isset($data['id'], $context['resource_class'])) {
8✔
76
            $parentAllowedAttributes = parent::getAllowedAttributes($class, $context, true);
1✔
77
            if (\is_array($parentAllowedAttributes) && !\in_array('id', $parentAllowedAttributes, true)) {
1✔
78
                unset($data['id']);
1✔
79
            }
80
        }
81

82
        return parent::denormalize($data, $class, $format, $context);
8✔
83
    }
84

85
    private function updateObjectToPopulate(array $data, array &$context): void
86
    {
87
        try {
88
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri((string) $data['id'], $context + ['fetch_data' => true]);
×
89
        } catch (InvalidArgumentException) {
×
90
            $operation = $this->resourceMetadataCollectionFactory?->create($context['resource_class'])->getOperation();
×
91
            if (
92
                !$operation || (
×
93
                    null !== ($context['uri_variables'] ?? null)
×
94
                    && $operation instanceof HttpOperation
×
95
                    && \count($operation->getUriVariables() ?? []) > 1
×
96
                )
97
            ) {
98
                throw new InvalidArgumentException('Cannot find object to populate, use JSON-LD or specify an IRI at path "id".');
×
99
            }
100
            $uriVariables = $this->getContextUriVariables($data, $operation, $context);
×
101
            $iri = $this->iriConverter->getIriFromResource($context['resource_class'], UrlGeneratorInterface::ABS_PATH, $operation, ['uri_variables' => $uriVariables]);
×
102

103
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($iri, $context + ['fetch_data' => true]);
×
104
        }
105
    }
106

107
    private function getContextUriVariables(array $data, $operation, array $context): array
108
    {
109
        $uriVariables = $context['uri_variables'] ?? [];
×
110

111
        $operationUriVariables = $operation->getUriVariables();
×
112
        if ((null !== $uriVariable = array_shift($operationUriVariables)) && \count($uriVariable->getIdentifiers())) {
×
113
            $identifier = $uriVariable->getIdentifiers()[0];
×
114
            if (isset($data[$identifier])) {
×
115
                $uriVariables[$uriVariable->getParameterName()] = $data[$identifier];
×
116
            }
117
        }
118

119
        return $uriVariables;
×
120
    }
121

122
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
123
    {
124
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
29✔
125
        if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
29✔
126
            $allowedAttributes = array_merge($allowedAttributes, ['id']);
7✔
127
        }
128

129
        return $allowedAttributes;
29✔
130
    }
131
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc