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

api-platform / core / 20903291093

11 Jan 2026 10:58PM UTC coverage: 20.146% (-8.7%) from 28.875%
20903291093

Pull #7667

github

VincentLanglet
Try
Pull Request #7667: POC NameConverterAwareInterface

0 of 20 new or added lines in 7 files covered. (0.0%)

14884 existing lines in 487 files now uncovered.

11580 of 57481 relevant lines covered (20.15%)

27.5 hits per line

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

98.11
/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);
837✔
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);
511✔
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) : [];
784✔
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);
476✔
UNCOV
102
        $outputClass = $this->getOutputClass($context);
476✔
103

UNCOV
104
        if ($outputClass && !($context['item_uri_template'] ?? null)) {
476✔
UNCOV
105
            return parent::normalize($object, $format, $context);
8✔
106
        }
107

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

UNCOV
122
            if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
15✔
UNCOV
123
                $context['output']['operation'] = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
2✔
124
            }
125

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

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

UNCOV
135
        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)) {
476✔
UNCOV
136
            $context['iri'] = $iri;
476✔
UNCOV
137
            $metadata['@id'] = $iri;
476✔
138
        }
139

UNCOV
140
        $context['api_normalize'] = true;
476✔
141

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

UNCOV
147
        $operation = $context['operation'] ?? null;
476✔
UNCOV
148
        if ($isResourceClass && !$operation) {
476✔
UNCOV
149
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
223✔
150
        }
151

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

UNCOV
160
        return $metadata + $data;
476✔
161
    }
162

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

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

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

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

UNCOV
195
        return parent::denormalize($data, $class, $format, $context);
156✔
196
    }
197

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

UNCOV
205
        return $allowedAttributes;
478✔
206
    }
207
}
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