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

api-platform / core / 13471447230

22 Feb 2025 09:00AM UTC coverage: 8.516%. Remained the same
13471447230

push

github

web-flow
feat: add checkMode parameter to control json schema validation (#6974)

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

10870 existing lines in 366 files now uncovered.

13370 of 156994 relevant lines covered (8.52%)

22.87 hits per line

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

97.96
/src/GraphQl/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\GraphQl\Serializer;
15

16
use ApiPlatform\GraphQl\State\Provider\NoopProvider;
17
use ApiPlatform\Metadata\ApiProperty;
18
use ApiPlatform\Metadata\GraphQl\Query;
19
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
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\Util\ClassInfoTrait;
27
use ApiPlatform\Serializer\CacheKeyTrait;
28
use ApiPlatform\Serializer\ItemNormalizer as BaseItemNormalizer;
29
use Psr\Log\LoggerInterface;
30
use Psr\Log\NullLogger;
31
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
32
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
33
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
34
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
35

36
/**
37
 * GraphQL normalizer.
38
 *
39
 * @author Kévin Dunglas <dunglas@gmail.com>
40
 */
41
final class ItemNormalizer extends BaseItemNormalizer
42
{
43
    use CacheKeyTrait;
44
    use ClassInfoTrait;
45

46
    public const FORMAT = 'graphql';
47
    public const ITEM_RESOURCE_CLASS_KEY = '#itemResourceClass';
48
    public const ITEM_IDENTIFIERS_KEY = '#itemIdentifiers';
49

50
    private array $safeCacheKeysCache = [];
51

52
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, private readonly IdentifiersExtractorInterface $identifiersExtractor, ResourceClassResolverInterface $resourceClassResolver, ?PropertyAccessorInterface $propertyAccessor = null, ?NameConverterInterface $nameConverter = null, ?ClassMetadataFactoryInterface $classMetadataFactory = null, ?LoggerInterface $logger = null, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ?ResourceAccessCheckerInterface $resourceAccessChecker = null)
53
    {
UNCOV
54
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $logger ?: new NullLogger(), $resourceMetadataCollectionFactory, $resourceAccessChecker);
2,004✔
55
    }
56

57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
61
    {
UNCOV
62
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
215✔
63
    }
64

65
    public function getSupportedTypes($format): array
66
    {
UNCOV
67
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
1,818✔
68
    }
69

70
    /**
71
     * {@inheritdoc}
72
     *
73
     * @param array<string, mixed> $context
74
     *
75
     * @throws UnexpectedValueException
76
     */
77
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
78
    {
UNCOV
79
        $resourceClass = $this->getObjectClass($object);
215✔
80

UNCOV
81
        if ($this->getOutputClass($context)) {
215✔
82
            $context['graphql_identifiers'] = [
6✔
83
                self::ITEM_RESOURCE_CLASS_KEY => $context['operation']->getClass(),
6✔
84
                self::ITEM_IDENTIFIERS_KEY => $this->identifiersExtractor->getIdentifiersFromItem($object, $context['operation'] ?? null),
6✔
85
            ];
6✔
86

87
            return parent::normalize($object, $format, $context);
6✔
88
        }
89

UNCOV
90
        if ($this->isCacheKeySafe($context)) {
215✔
UNCOV
91
            $context['cache_key'] = $this->getCacheKey($format, $context);
181✔
92
        }
93

UNCOV
94
        unset($context['operation_name'], $context['operation']); // Remove operation and operation_name only when cache key has been created
215✔
UNCOV
95
        $data = parent::normalize($object, $format, $context);
215✔
UNCOV
96
        if (!\is_array($data)) {
215✔
97
            throw new UnexpectedValueException('Expected data to be an array.');
×
98
        }
99

UNCOV
100
        if (isset($context['graphql_identifiers'])) {
215✔
101
            $data += $context['graphql_identifiers'];
6✔
UNCOV
102
        } elseif (!($context['no_resolver_data'] ?? false)) {
211✔
UNCOV
103
            $data[self::ITEM_RESOURCE_CLASS_KEY] = $resourceClass;
209✔
UNCOV
104
            $data[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($object, $context['operation'] ?? null);
209✔
105
        }
106

UNCOV
107
        return $data;
215✔
108
    }
109

110
    /**
111
     * {@inheritdoc}
112
     */
113
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
114
    {
115
        // check for nested collection
116
        $operation = $this->resourceMetadataCollectionFactory?->create($resourceClass)->getOperation(forceCollection: true, forceGraphQl: true);
41✔
117
        if ($operation instanceof Query && $operation->getNested() && !$operation->getResolver() && (!$operation->getProvider() || NoopProvider::class === $operation->getProvider())) {
41✔
118
            return [...$attributeValue];
4✔
119
        }
120

121
        // to-many are handled directly by the GraphQL resolver
122
        return [];
41✔
123
    }
124

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

133
    /**
134
     * {@inheritdoc}
135
     */
136
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
137
    {
UNCOV
138
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
223✔
139

UNCOV
140
        if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
223✔
141
            $allowedAttributes[] = '_id';
9✔
142
            array_splice($allowedAttributes, (int) $indexId, 1);
9✔
143
        }
144

UNCOV
145
        return $allowedAttributes;
223✔
146
    }
147

148
    /**
149
     * {@inheritdoc}
150
     */
151
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = []): void
152
    {
153
        if ('_id' === $attribute) {
50✔
154
            $attribute = 'id';
3✔
155
        }
156

157
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
50✔
158
    }
159

160
    /**
161
     * Check if any property contains a security grants, which makes the cache key not safe,
162
     * as allowed_properties can differ for 2 instances of the same object.
163
     */
164
    private function isCacheKeySafe(array $context): bool
165
    {
UNCOV
166
        if (!isset($context['resource_class']) || !$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
215✔
167
            return false;
10✔
168
        }
UNCOV
169
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
209✔
UNCOV
170
        if (isset($this->safeCacheKeysCache[$resourceClass])) {
209✔
UNCOV
171
            return $this->safeCacheKeysCache[$resourceClass];
68✔
172
        }
UNCOV
173
        $options = $this->getFactoryOptions($context);
209✔
UNCOV
174
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
209✔
175

UNCOV
176
        $this->safeCacheKeysCache[$resourceClass] = true;
209✔
UNCOV
177
        foreach ($propertyNames as $propertyName) {
209✔
UNCOV
178
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
209✔
UNCOV
179
            if (null !== $propertyMetadata->getSecurity()) {
209✔
180
                $this->safeCacheKeysCache[$resourceClass] = false;
40✔
181
                break;
40✔
182
            }
183
        }
184

UNCOV
185
        return $this->safeCacheKeysCache[$resourceClass];
209✔
186
    }
187
}
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