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

api-platform / core / 9869461710

10 Jul 2024 06:43AM UTC coverage: 63.421%. Remained the same
9869461710

push

github

soyuka
cs(jsonld): non-nullable not needed

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

589 existing lines in 21 files now uncovered.

11178 of 17625 relevant lines covered (63.42%)

53.23 hits per line

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

66.67
/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\Api\IriConverterInterface as LegacyIriConverterInterface;
17
use ApiPlatform\Api\ResourceClassResolverInterface as LegacyResourceClassResolverInterface;
18
use ApiPlatform\JsonLd\AnonymousContextBuilderInterface;
19
use ApiPlatform\JsonLd\ContextBuilderInterface;
20
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
21
use ApiPlatform\Metadata\HttpOperation;
22
use ApiPlatform\Metadata\IriConverterInterface;
23
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
25
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
26
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
27
use ApiPlatform\Metadata\ResourceClassResolverInterface;
28
use ApiPlatform\Metadata\UrlGeneratorInterface;
29
use ApiPlatform\Metadata\Util\ClassInfoTrait;
30
use ApiPlatform\Serializer\AbstractItemNormalizer;
31
use ApiPlatform\Serializer\ContextTrait;
32
use ApiPlatform\Serializer\TagCollectorInterface;
33
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
34
use Symfony\Component\Serializer\Exception\LogicException;
35
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
36
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
37
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
38

39
/**
40
 * Converts between objects and array including JSON-LD and Hydra metadata.
41
 *
42
 * @author Kévin Dunglas <dunglas@gmail.com>
43
 */
44
final class ItemNormalizer extends AbstractItemNormalizer
45
{
46
    use ClassInfoTrait;
47
    use ContextTrait;
48
    use JsonLdContextTrait;
49

50
    public const FORMAT = 'jsonld';
51
    private const JSONLD_KEYWORDS = [
52
        '@context',
53
        '@direction',
54
        '@graph',
55
        '@id',
56
        '@import',
57
        '@included',
58
        '@index',
59
        '@json',
60
        '@language',
61
        '@list',
62
        '@nest',
63
        '@none',
64
        '@prefix',
65
        '@propagate',
66
        '@protected',
67
        '@reverse',
68
        '@set',
69
        '@type',
70
        '@value',
71
        '@version',
72
        '@vocab',
73
    ];
74

75
    public function __construct(ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface|LegacyIriConverterInterface $iriConverter, ResourceClassResolverInterface|LegacyResourceClassResolverInterface $resourceClassResolver, private readonly ContextBuilderInterface $contextBuilder, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ?ResourceAccessCheckerInterface $resourceAccessChecker = null, protected ?TagCollectorInterface $tagCollector = null)
76
    {
77
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker, $tagCollector);
275✔
78
    }
79

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

88
    public function getSupportedTypes($format): array
89
    {
90
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
215✔
91
    }
92

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

102
        if ($this->getOutputClass($context)) {
120✔
103
            return parent::normalize($object, $format, $context);
8✔
104
        }
105

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

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

124
        // maybe not needed anymore
125
        if (isset($context['operation']) && $previousResourceClass !== $resourceClass) {
120✔
126
            unset($context['operation'], $context['operation_name']);
×
127
        }
128

129
        if (true === ($context['force_iri_generation'] ?? true) && $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context)) {
120✔
130
            $context['iri'] = $iri;
120✔
131
            $metadata['@id'] = $iri;
120✔
132
        }
133

134
        $context['api_normalize'] = true;
120✔
135

136
        $data = parent::normalize($object, $format, $context);
120✔
137
        if (!\is_array($data)) {
120✔
138
            return $data;
×
139
        }
140

141
        if (!isset($metadata['@type']) && $isResourceClass) {
120✔
142
            $operation = $context['operation'] ?? $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
112✔
143

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

151
        return $metadata + $data;
120✔
152
    }
153

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

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

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

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

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

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

196
        return $allowedAttributes;
120✔
197
    }
198
}
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