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

api-platform / core / 13200284839

07 Feb 2025 12:56PM UTC coverage: 0.0% (-8.2%) from 8.164%
13200284839

Pull #6952

github

web-flow
Merge 519fbf8cc into 62377f880
Pull Request #6952: fix: errors retrieval and documentation

0 of 206 new or added lines in 17 files covered. (0.0%)

10757 existing lines in 366 files now uncovered.

0 of 47781 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/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);
×
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);
×
63
    }
64

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

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

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

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

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

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

UNCOV
107
        return $data;
×
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);
×
117
        if ($operation instanceof Query && $operation->getNested() && !$operation->getResolver() && (!$operation->getProvider() || NoopProvider::class === $operation->getProvider())) {
×
118
            return [...$attributeValue];
×
119
        }
120

121
        // to-many are handled directly by the GraphQL resolver
122
        return [];
×
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);
×
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);
×
139

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

UNCOV
145
        return $allowedAttributes;
×
146
    }
147

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

157
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
×
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'])) {
×
167
            return false;
×
168
        }
UNCOV
169
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
×
UNCOV
170
        if (isset($this->safeCacheKeysCache[$resourceClass])) {
×
UNCOV
171
            return $this->safeCacheKeysCache[$resourceClass];
×
172
        }
UNCOV
173
        $options = $this->getFactoryOptions($context);
×
UNCOV
174
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
×
175

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

UNCOV
185
        return $this->safeCacheKeysCache[$resourceClass];
×
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