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

api-platform / core / 19337755357

13 Nov 2025 04:03PM UTC coverage: 0.0%. Remained the same
19337755357

push

github

soyuka
Merge 4.2

0 of 298 new or added lines in 18 files covered. (0.0%)

61 existing lines in 11 files now uncovered.

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

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

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

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

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

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

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

142
        $context['api_normalize'] = true;
×
143

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

UNCOV
149
        $operation = $context['operation'] ?? null;
×
150

151
        if ($this->operationMetadataFactory && isset($context['item_uri_template']) && !$operation) {
×
152
            $operation = $this->operationMetadataFactory->create($context['item_uri_template']);
×
153
        }
154

UNCOV
155
        if ($isResourceClass && !$operation) {
×
156
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
157
        }
158

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

167
        return $metadata + $data;
×
168
    }
169

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

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

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

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

UNCOV
202
        return parent::denormalize($data, $class, $format, $context);
×
203
    }
204

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

UNCOV
212
        return $allowedAttributes;
×
213
    }
214
}
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