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

api-platform / core / 14635100171

24 Apr 2025 06:39AM UTC coverage: 8.271% (+0.02%) from 8.252%
14635100171

Pull #6904

github

web-flow
Merge c9cefd82e into a3e5e53ea
Pull Request #6904: feat(graphql): added support for graphql subscriptions to work for actions

0 of 73 new or added lines in 3 files covered. (0.0%)

1999 existing lines in 144 files now uncovered.

13129 of 158728 relevant lines covered (8.27%)

13.6 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
    {
54
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $logger ?: new NullLogger(), $resourceMetadataCollectionFactory, $resourceAccessChecker);
1,160✔
55
    }
56

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

65
    public function getSupportedTypes($format): array
66
    {
67
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
1,041✔
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
    {
79
        $resourceClass = $this->getObjectClass($object);
114✔
80

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

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

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

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

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

109
        return $data;
114✔
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
UNCOV
118
        $operation = $this->resourceMetadataCollectionFactory?->create($resourceClass)->getOperation(forceCollection: true, forceGraphQl: true);
20✔
UNCOV
119
        if ($operation instanceof Query && $operation->getNested() && !$operation->getResolver() && (!$operation->getProvider() || NoopProvider::class === $operation->getProvider())) {
20✔
UNCOV
120
            return [...$attributeValue];
2✔
121
        }
122

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

127
    /**
128
     * {@inheritdoc}
129
     */
130
    public function supportsDenormalization(mixed $data, string $type, ?string $format = null, array $context = []): bool
131
    {
UNCOV
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
    {
140
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
117✔
141

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

147
        return $allowedAttributes;
117✔
148
    }
149

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

UNCOV
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
    {
168
        if (!isset($context['resource_class']) || !$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
114✔
UNCOV
169
            return false;
4✔
170
        }
171
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
112✔
172
        if (isset($this->safeCacheKeysCache[$resourceClass])) {
112✔
173
            return $this->safeCacheKeysCache[$resourceClass];
37✔
174
        }
175
        $options = $this->getFactoryOptions($context);
112✔
176
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
112✔
177

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

187
        return $this->safeCacheKeysCache[$resourceClass];
112✔
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