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

api-platform / core / 17723449516

15 Sep 2025 05:52AM UTC coverage: 0.0% (-22.6%) from 22.578%
17723449516

Pull #7383

github

web-flow
Merge fa5b61e35 into 949c3c975
Pull Request #7383: fix(metadata): compute isWritable during updates

0 of 6 new or added lines in 4 files covered. (0.0%)

11356 existing lines in 371 files now uncovered.

0 of 48868 relevant lines covered (0.0%)

0.0 hits per line

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

0.0
/src/JsonLd/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\JsonLd\Serializer;
15

16
use ApiPlatform\JsonLd\AnonymousContextBuilderInterface;
17
use ApiPlatform\JsonLd\ContextBuilderInterface;
18
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
19
use ApiPlatform\Metadata\HttpOperation;
20
use ApiPlatform\Metadata\IriConverterInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
25
use ApiPlatform\Metadata\ResourceClassResolverInterface;
26
use ApiPlatform\Metadata\UrlGeneratorInterface;
27
use ApiPlatform\Metadata\Util\ClassInfoTrait;
28
use ApiPlatform\Serializer\AbstractItemNormalizer;
29
use ApiPlatform\Serializer\ContextTrait;
30
use ApiPlatform\Serializer\TagCollectorInterface;
31
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
32
use Symfony\Component\Serializer\Exception\LogicException;
33
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
34
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
35
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
36

37
/**
38
 * Converts between objects and array including JSON-LD and Hydra metadata.
39
 *
40
 * @author Kévin Dunglas <dunglas@gmail.com>
41
 */
42
final class ItemNormalizer extends AbstractItemNormalizer
43
{
44
    use ClassInfoTrait;
45
    use ContextTrait;
46
    use JsonLdContextTrait;
47

48
    public const FORMAT = 'jsonld';
49
    private const JSONLD_KEYWORDS = [
50
        '@context',
51
        '@direction',
52
        '@graph',
53
        '@id',
54
        '@import',
55
        '@included',
56
        '@index',
57
        '@json',
58
        '@language',
59
        '@list',
60
        '@nest',
61
        '@none',
62
        '@prefix',
63
        '@propagate',
64
        '@protected',
65
        '@reverse',
66
        '@set',
67
        '@type',
68
        '@value',
69
        '@version',
70
        '@vocab',
71
    ];
72

73
    public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
74
    {
UNCOV
75
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
×
76
    }
77

78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
82
    {
UNCOV
83
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
×
84
    }
85

86
    public function getSupportedTypes($format): array
87
    {
UNCOV
88
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
×
89
    }
90

91
    /**
92
     * {@inheritdoc}
93
     *
94
     * @throws LogicException
95
     */
96
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
97
    {
UNCOV
98
        $resourceClass = $this->getObjectClass($object);
×
99

UNCOV
100
        if ($this->getOutputClass($context)) {
×
UNCOV
101
            return parent::normalize($object, $format, $context);
×
102
        }
103

104
        // TODO: we should not remove the resource_class in the normalizeRawCollection as we would find out anyway that it's not the same as the requested one
UNCOV
105
        $previousResourceClass = $context['resource_class'] ?? null;
×
UNCOV
106
        $metadata = [];
×
UNCOV
107
        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
×
UNCOV
108
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
×
UNCOV
109
            $context = $this->initContext($resourceClass, $context);
×
UNCOV
110
            $metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
×
UNCOV
111
        } elseif ($this->contextBuilder instanceof AnonymousContextBuilderInterface) {
×
UNCOV
112
            if ($context['api_collection_sub_level'] ?? false) {
×
UNCOV
113
                unset($context['api_collection_sub_level']);
×
UNCOV
114
                $context['output']['gen_id'] ??= true;
×
UNCOV
115
                $context['output']['iri'] = null;
×
116
            }
117

UNCOV
118
            if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
×
UNCOV
119
                $context['output']['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
120
            }
121

122
            // We should improve what's behind the context creation, its probably more complicated then it should
UNCOV
123
            $metadata = $this->createJsonLdContext($this->contextBuilder, $object, $context);
×
124
        }
125

126
        // Special case: non-resource got serialized and contains a resource therefore we need to reset part of the context
UNCOV
127
        if ($previousResourceClass !== $resourceClass) {
×
UNCOV
128
            unset($context['operation'], $context['operation_name'], $context['output']);
×
129
        }
130

UNCOV
131
        if (true === ($context['output']['gen_id'] ?? true) && true === ($context['force_iri_generation'] ?? true) && $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context)) {
×
UNCOV
132
            $context['iri'] = $iri;
×
UNCOV
133
            $metadata['@id'] = $iri;
×
134
        }
135

UNCOV
136
        $context['api_normalize'] = true;
×
137

UNCOV
138
        $data = parent::normalize($object, $format, $context);
×
UNCOV
139
        if (!\is_array($data)) {
×
140
            return $data;
×
141
        }
142

UNCOV
143
        $operation = $context['operation'] ?? null;
×
UNCOV
144
        if ($isResourceClass && !$operation) {
×
UNCOV
145
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
146
        }
147

UNCOV
148
        if (!isset($metadata['@type']) && $operation) {
×
UNCOV
149
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
UNCOV
150
            if (null === $types) {
×
UNCOV
151
                $types = [$operation->getShortName()];
×
152
            }
UNCOV
153
            $metadata['@type'] = 1 === \count($types) ? $types[0] : $types;
×
154
        }
155

UNCOV
156
        return $metadata + $data;
×
157
    }
158

159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
163
    {
UNCOV
164
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
165
    }
166

167
    /**
168
     * {@inheritdoc}
169
     *
170
     * @throws NotNormalizableValueException
171
     */
172
    public function denormalize(mixed $data, string $class, ?string $format = null, array $context = []): mixed
173
    {
174
        // Avoid issues with proxies if we populated the object
UNCOV
175
        if (isset($data['@id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
×
176
            if (true !== ($context['api_allow_update'] ?? true)) {
×
177
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
×
178
            }
179

180
            try {
181
                $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['@id'], $context + ['fetch_data' => true], $context['operation'] ?? null);
×
182
            } catch (ItemNotFoundException $e) {
×
183
                $operation = $context['operation'] ?? null;
×
184

185
                if (!('PUT' === $operation?->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? true))) {
×
186
                    throw $e;
×
187
                }
188
            }
189
        }
190

UNCOV
191
        return parent::denormalize($data, $class, $format, $context);
×
192
    }
193

194
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
195
    {
UNCOV
196
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
UNCOV
197
        if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
×
UNCOV
198
            $allowedAttributes = array_merge($allowedAttributes, self::JSONLD_KEYWORDS);
×
199
        }
200

UNCOV
201
        return $allowedAttributes;
×
202
    }
203
}
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