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

api-platform / core / 16531587208

25 Jul 2025 09:05PM UTC coverage: 0.0% (-22.1%) from 22.07%
16531587208

Pull #7225

github

web-flow
Merge 23f449a58 into 02a764950
Pull Request #7225: feat: json streamer

0 of 294 new or added lines in 31 files covered. (0.0%)

11514 existing lines in 375 files now uncovered.

0 of 51976 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
    public function getSupportedTypes($format): array
87
    {
UNCOV
88
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
×
89
    }
90

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

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

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

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

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

UNCOV
127
        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
128
            $context['iri'] = $iri;
×
UNCOV
129
            $metadata['@id'] = $iri;
×
130
        }
131

UNCOV
132
        $context['api_normalize'] = true;
×
133

UNCOV
134
        $data = parent::normalize($object, $format, $context);
×
UNCOV
135
        if (!\is_array($data)) {
×
136
            return $data;
×
137
        }
138

UNCOV
139
        $operation = $context['operation'] ?? null;
×
UNCOV
140
        if ($isResourceClass && !$operation) {
×
UNCOV
141
            $operation = $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
×
142
        }
143

UNCOV
144
        if (!isset($metadata['@type']) && $operation) {
×
UNCOV
145
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
×
UNCOV
146
            if (null === $types) {
×
UNCOV
147
                $types = [$operation->getShortName()];
×
148
            }
UNCOV
149
            $metadata['@type'] = 1 === \count($types) ? $types[0] : $types;
×
150
        }
151

UNCOV
152
        return $metadata + $data;
×
153
    }
154

155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
159
    {
UNCOV
160
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
161
    }
162

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

176
            try {
177
                $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['@id'], $context + ['fetch_data' => true], $context['operation'] ?? null);
×
178
            } catch (ItemNotFoundException $e) {
×
179
                $operation = $context['operation'] ?? null;
×
180

181
                if (!('PUT' === $operation?->getMethod() && ($operation->getExtraProperties()['standard_put'] ?? true))) {
×
182
                    throw $e;
×
183
                }
184
            }
185
        }
186

UNCOV
187
        return parent::denormalize($data, $class, $format, $context);
×
188
    }
189

190
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
191
    {
UNCOV
192
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
UNCOV
193
        if (\is_array($allowedAttributes) && ($context['api_denormalize'] ?? false)) {
×
UNCOV
194
            $allowedAttributes = array_merge($allowedAttributes, self::JSONLD_KEYWORDS);
×
195
        }
196

UNCOV
197
        return $allowedAttributes;
×
198
    }
199
}
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