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

api-platform / core / 15133993414

20 May 2025 09:30AM UTC coverage: 26.313% (-1.2%) from 27.493%
15133993414

Pull #7161

github

web-flow
Merge e2c03d45f into 5459ba375
Pull Request #7161: fix(metadata): infer parameter string type from schema

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

11019 existing lines in 363 files now uncovered.

12898 of 49018 relevant lines covered (26.31%)

34.33 hits per line

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

98.0
/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);
950✔
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);
104✔
63
    }
64

65
    public function getSupportedTypes($format): array
66
    {
UNCOV
67
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
855✔
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);
104✔
80

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

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

UNCOV
90
        if ($this->isCacheKeySafe($context)) {
104✔
UNCOV
91
            $context['cache_key'] = $this->getCacheKey($format, $context);
88✔
92
        } else {
UNCOV
93
            $context['cache_key'] = false;
25✔
94
        }
95

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

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

UNCOV
109
        return $data;
104✔
110
    }
111

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

123
        // to-many are handled directly by the GraphQL resolver
124
        return [];
20✔
125
    }
126

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

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

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

UNCOV
147
        return $allowedAttributes;
107✔
148
    }
149

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

159
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
23✔
160
    }
161

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

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

UNCOV
187
        return $this->safeCacheKeysCache[$resourceClass];
102✔
188
    }
189
}
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