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

api-platform / core / 3712739783

pending completion
3712739783

Pull #5254

github

GitHub
Merge 9dfa88fa6 into ac711530f
Pull Request #5254: [OpenApi] Add ApiResource::openapi and deprecate openapiContext

199 of 199 new or added lines in 6 files covered. (100.0%)

7494 of 12363 relevant lines covered (60.62%)

67.55 hits per line

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

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

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

46
    public const FORMAT = 'jsonld';
47

48
    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)
49
    {
50
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker);
649✔
51
    }
52

53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
57
    {
58
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
543✔
59
    }
60

61
    /**
62
     * {@inheritdoc}
63
     *
64
     * @throws LogicException
65
     */
66
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
67
    {
68
        $resourceClass = $this->getObjectClass($object);
290✔
69

70
        if ($this->getOutputClass($context)) {
290✔
71
            return parent::normalize($object, $format, $context);
9✔
72
        }
73

74
        // 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
75
        $previousResourceClass = $context['resource_class'] ?? null;
290✔
76
        $metadata = [];
290✔
77
        if ($isResourceClass = $this->resourceClassResolver->isResourceClass($resourceClass)) {
290✔
78
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
282✔
79
            $context = $this->initContext($resourceClass, $context);
282✔
80
            $metadata = $this->addJsonLdContext($this->contextBuilder, $resourceClass, $context);
282✔
81
        } elseif ($this->contextBuilder instanceof AnonymousContextBuilderInterface) {
9✔
82
            if ($context['api_collection_sub_level'] ?? false) {
9✔
83
                unset($context['api_collection_sub_level']);
4✔
84
                $context['output']['genid'] = true;
4✔
85
                $context['output']['iri'] = null;
4✔
86
            }
87

88
            // We should improve what's behind the context creation, its probably more complicated then it should
89
            $metadata = $this->createJsonLdContext($this->contextBuilder, $object, $context);
9✔
90
        }
91

92
        // maybe not needed anymore
93
        if (isset($context['operation']) && $previousResourceClass !== $resourceClass) {
290✔
94
            unset($context['operation'], $context['operation_name']);
4✔
95
        }
96

97
        if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate') && ($itemUriTemplate = $operation->getItemUriTemplate())) {
290✔
98
            $context['item_uri_template'] = $itemUriTemplate;
×
99
        }
100

101
        if ($iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context)) {
290✔
102
            $context['iri'] = $iri;
290✔
103
            $metadata['@id'] = $iri;
290✔
104
        }
105

106
        $context['api_normalize'] = true;
290✔
107

108
        $data = parent::normalize($object, $format, $context);
290✔
109
        if (!\is_array($data)) {
290✔
110
            return $data;
2✔
111
        }
112

113
        if (!isset($metadata['@type']) && $isResourceClass) {
290✔
114
            $operation = $context['operation'] ?? $this->resourceMetadataCollectionFactory->create($resourceClass)->getOperation();
282✔
115

116
            $types = $operation instanceof HttpOperation ? $operation->getTypes() : null;
282✔
117
            if (null === $types) {
282✔
118
                $types = [$operation->getShortName()];
280✔
119
            }
120
            $metadata['@type'] = 1 === \count($types) ? $types[0] : $types;
282✔
121
        }
122

123
        return $metadata + $data;
290✔
124
    }
125

126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
130
    {
131
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
180✔
132
    }
133

134
    /**
135
     * {@inheritdoc}
136
     *
137
     * @throws NotNormalizableValueException
138
     */
139
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
140
    {
141
        // Avoid issues with proxies if we populated the object
142
        if (isset($data['@id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
97✔
143
            if (true !== ($context['api_allow_update'] ?? true)) {
5✔
144
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
1✔
145
            }
146

147
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($data['@id'], $context + ['fetch_data' => true]);
4✔
148
        }
149

150
        return parent::denormalize($data, $class, $format, $context);
96✔
151
    }
152
}
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