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

api-platform / core / 18060089452

27 Sep 2025 12:57PM UTC coverage: 0.0% (-21.8%) from 21.793%
18060089452

Pull #7397

github

web-flow
Merge 479f46b8d into abe0438be
Pull Request #7397: fix(jsonschema/jsonld): make `@id` and `@type` properties required only in the JSON-LD schema for output

0 of 15 new or added lines in 1 file covered. (0.0%)

11967 existing lines in 393 files now uncovered.

0 of 53914 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
    /**
87
     * @param string|null $format
88
     */
89
    public function getSupportedTypes($format): array
90
    {
UNCOV
91
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
×
92
    }
93

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

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

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

UNCOV
121
            if ($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;
×
UNCOV
147
        if ($isResourceClass && !$operation) {
×
UNCOV
148
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
149
        }
150

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

UNCOV
159
        return $metadata + $data;
×
160
    }
161

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

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

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

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

UNCOV
194
        return parent::denormalize($data, $class, $format, $context);
×
195
    }
196

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

UNCOV
204
        return $allowedAttributes;
×
205
    }
206
}
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