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

api-platform / core / 20684544647

03 Jan 2026 11:39PM UTC coverage: 28.861%. First build
20684544647

Pull #7643

github

web-flow
Merge 6c145d0b3 into 0e899fa81
Pull Request #7643: refactor: make method parameter names match interfaces

112 of 164 new or added lines in 34 files covered. (68.29%)

16767 of 58096 relevant lines covered (28.86%)

78.47 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
    {
75
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
2,309✔
76
    }
77

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

86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function getSupportedTypes(?string $format): array
90
    {
91
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
2,044✔
92
    }
93

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

104
        if ($outputClass && !($context['item_uri_template'] ?? null)) {
1,309✔
105
            return parent::normalize($data, $format, $context);
23✔
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
109
        $previousResourceClass = $context['resource_class'] ?? null;
1,309✔
110
        $metadata = [];
1,309✔
111
        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass) && (null === $previousResourceClass || $this->resourceClassResolver->isResourceClass($previousResourceClass))) {
1,309✔
112
            $resourceClass = $this->resourceClassResolver->getResourceClass($data, $previousResourceClass);
1,270✔
113
            $context = $this->initContext($resourceClass, $context);
1,270✔
114
            $metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
1,270✔
115
        } elseif ($this->contextBuilder instanceof AnonymousContextBuilderInterface) {
49✔
116
            if ($context['api_collection_sub_level'] ?? false) {
49✔
117
                unset($context['api_collection_sub_level']);
24✔
118
                $context['output']['gen_id'] ??= true;
24✔
119
                $context['output']['iri'] = null;
24✔
120
            }
121

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

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

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

135
        if (true === ($context['output']['gen_id'] ?? true) && true === ($context['force_iri_generation'] ?? true) && $iri = $this->iriConverter->getIriFromResource($data, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context)) {
1,309✔
136
            $context['iri'] = $iri;
1,309✔
137
            $metadata['@id'] = $iri;
1,309✔
138
        }
139

140
        $context['api_normalize'] = true;
1,309✔
141

142
        $normalizedData = parent::normalize($data, $format, $context);
1,309✔
143
        if (!\is_array($normalizedData)) {
1,309✔
NEW
144
            return $normalizedData;
4✔
145
        }
146

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

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

160
        return $metadata + $normalizedData;
1,309✔
161
    }
162

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

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

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

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

195
        return parent::denormalize($data, $type, $format, $context);
281✔
196
    }
197

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

205
        return $allowedAttributes;
1,313✔
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