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

api-platform / core / 19173909613

07 Nov 2025 04:03PM UTC coverage: 0.0% (-22.0%) from 22.042%
19173909613

Pull #7515

github

web-flow
Merge 63ab5112d into 3df65aa86
Pull Request #7515: fix(jsonld): read identifier with itemUriTemplate

0 of 11 new or added lines in 2 files covered. (0.0%)

11197 existing lines in 362 files now uncovered.

0 of 49873 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\Operation\Factory\OperationMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
23
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
24
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
25
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
26
use ApiPlatform\Metadata\ResourceClassResolverInterface;
27
use ApiPlatform\Metadata\UrlGeneratorInterface;
28
use ApiPlatform\Metadata\Util\ClassInfoTrait;
29
use ApiPlatform\Serializer\AbstractItemNormalizer;
30
use ApiPlatform\Serializer\ContextTrait;
31
use ApiPlatform\Serializer\TagCollectorInterface;
32
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
33
use Symfony\Component\Serializer\Exception\LogicException;
34
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
35
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
36
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
37

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

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

74
    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, private ?OperationMetadataFactoryInterface $operationMetadataFactory = null)
75
    {
UNCOV
76
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
×
77
    }
78

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

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

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

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

105
        // 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
106
        $previousResourceClass = $context['resource_class'] ?? null;
×
UNCOV
107
        $metadata = [];
×
UNCOV
108
        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
×
UNCOV
109
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $previousResourceClass);
×
UNCOV
110
            $context = $this->initContext($resourceClass, $context);
×
UNCOV
111
            $metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
×
UNCOV
112
        } elseif ($this->contextBuilder instanceof AnonymousContextBuilderInterface) {
×
UNCOV
113
            if ($context['api_collection_sub_level'] ?? false) {
×
UNCOV
114
                unset($context['api_collection_sub_level']);
×
UNCOV
115
                $context['output']['gen_id'] ??= true;
×
UNCOV
116
                $context['output']['iri'] = null;
×
117
            }
118

NEW
119
            if (isset($context['item_uri_template']) && $this->operationMetadataFactory) {
×
NEW
120
                $context['output']['operation'] = $this->operationMetadataFactory->create($context['item_uri_template']);
×
NEW
121
            } elseif ($this->resourceClassResolver->isResourceClass($resourceClass)) {
×
UNCOV
122
                $context['output']['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
123
            }
124

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

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

UNCOV
134
        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
135
            $context['iri'] = $iri;
×
UNCOV
136
            $metadata['@id'] = $iri;
×
137
        }
138

UNCOV
139
        $context['api_normalize'] = true;
×
140

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

UNCOV
146
        $operation = $context['operation'] ?? null;
×
147

NEW
148
        if ($this->operationMetadataFactory && isset($context['item_uri_template']) && !$operation) {
×
NEW
149
            $operation = $this->operationMetadataFactory->create($context['item_uri_template']);
×
150
        }
151

UNCOV
152
        if ($isResourceClass && !$operation) {
×
UNCOV
153
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
154
        }
155

UNCOV
156
        if (!isset($metadata['@type']) && $operation) {
×
UNCOV
157
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
UNCOV
158
            if (null === $types) {
×
UNCOV
159
                $types = [$operation->getShortName()];
×
160
            }
UNCOV
161
            $metadata['@type'] = 1 === \count($types) ? $types[0] : $types;
×
162
        }
163

UNCOV
164
        return $metadata + $data;
×
165
    }
166

167
    /**
168
     * {@inheritdoc}
169
     */
170
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
171
    {
UNCOV
172
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
173
    }
174

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

188
            try {
189
                $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['@id'], $context + ['fetch_data' => true], $context['operation'] ?? null);
×
190
            } catch (ItemNotFoundException $e) {
×
191
                $operation = $context['operation'] ?? null;
×
192

193
                if (!('PUT' === $operation?->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? true))) {
×
194
                    throw $e;
×
195
                }
196
            }
197
        }
198

UNCOV
199
        return parent::denormalize($data, $class, $format, $context);
×
200
    }
201

202
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
203
    {
UNCOV
204
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
UNCOV
205
        if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
×
UNCOV
206
            $allowedAttributes = array_merge($allowedAttributes, self::JSONLD_KEYWORDS);
×
207
        }
208

UNCOV
209
        return $allowedAttributes;
×
210
    }
211
}
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

© 2026 Coveralls, Inc