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

api-platform / core / 17562281609

08 Sep 2025 07:47PM UTC coverage: 0.0% (-22.6%) from 22.604%
17562281609

Pull #7374

github

web-flow
Merge 0c2b4a90a into 6db55be8c
Pull Request #7374: fix(jsonld): various json streamer fixes

0 of 33 new or added lines in 2 files covered. (0.0%)

12082 existing lines in 401 files now uncovered.

0 of 52792 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
    /**
66
     * @param string|null $format
67
     */
68
    public function getSupportedTypes($format): array
69
    {
UNCOV
70
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
×
71
    }
72

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

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

90
            return parent::normalize($object, $format, $context);
×
91
        }
92

UNCOV
93
        if ($this->isCacheKeySafe($context)) {
×
UNCOV
94
            $context['cache_key'] = $this->getCacheKey($format, $context);
×
95
        } else {
UNCOV
96
            $context['cache_key'] = false;
×
97
        }
98

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

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

UNCOV
112
        return $data;
×
113
    }
114

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

126
        // to-many are handled directly by the GraphQL resolver
127
        return [];
×
128
    }
129

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

138
    /**
139
     * {@inheritdoc}
140
     */
141
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
142
    {
UNCOV
143
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
144

UNCOV
145
        if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
×
146
            $allowedAttributes[] = '_id';
×
147
            array_splice($allowedAttributes, (int) $indexId, 1);
×
148
        }
149

UNCOV
150
        return $allowedAttributes;
×
151
    }
152

153
    /**
154
     * {@inheritdoc}
155
     *
156
     * @param object      $object
157
     * @param string      $attribute
158
     * @param string|null $format
159
     */
160
    protected function setAttributeValue($object, $attribute, mixed $value, $format = null, array $context = []): void
161
    {
162
        if ('_id' === $attribute) {
×
163
            $attribute = 'id';
×
164
        }
165

166
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
×
167
    }
168

169
    /**
170
     * Check if any property contains a security grants, which makes the cache key not safe,
171
     * as allowed_properties can differ for 2 instances of the same object.
172
     */
173
    private function isCacheKeySafe(array $context): bool
174
    {
UNCOV
175
        if (!isset($context['resource_class']) || !$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
×
176
            return false;
×
177
        }
UNCOV
178
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
×
UNCOV
179
        if (isset($this->safeCacheKeysCache[$resourceClass])) {
×
UNCOV
180
            return $this->safeCacheKeysCache[$resourceClass];
×
181
        }
UNCOV
182
        $options = $this->getFactoryOptions($context);
×
UNCOV
183
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
×
184

UNCOV
185
        $this->safeCacheKeysCache[$resourceClass] = true;
×
UNCOV
186
        foreach ($propertyNames as $propertyName) {
×
UNCOV
187
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
×
UNCOV
188
            if (null !== $propertyMetadata->getSecurity()) {
×
UNCOV
189
                $this->safeCacheKeysCache[$resourceClass] = false;
×
UNCOV
190
                break;
×
191
            }
192
        }
193

UNCOV
194
        return $this->safeCacheKeysCache[$resourceClass];
×
195
    }
196
}
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