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

api-platform / core / 7407219156

04 Jan 2024 08:32AM UTC coverage: 35.357% (-1.9%) from 37.257%
7407219156

push

github

soyuka
cs: various fixes

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

425 existing lines in 27 files now uncovered.

10237 of 28953 relevant lines covered (35.36%)

27.07 hits per line

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

4.08
/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\Metadata\ApiProperty;
17
use ApiPlatform\Metadata\GraphQl\Query;
18
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
19
use ApiPlatform\Metadata\IriConverterInterface;
20
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\Util\ClassInfoTrait;
26
use ApiPlatform\Serializer\CacheKeyTrait;
27
use ApiPlatform\Serializer\ItemNormalizer as BaseItemNormalizer;
28
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface as LegacyResourceAccessCheckerInterface;
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
    /**
53
     * @param LegacyResourceAccessCheckerInterface|ResourceAccessCheckerInterface $resourceAccessChecker
54
     */
55
    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, $resourceAccessChecker = null)
56
    {
57
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $logger ?: new NullLogger(), $resourceMetadataCollectionFactory, $resourceAccessChecker);
116✔
58
    }
59

60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
64
    {
UNCOV
65
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
×
66
    }
67

68
    public function getSupportedTypes($format): array
69
    {
70
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
72✔
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
    {
82
        $resourceClass = $this->getObjectClass($object);
×
83

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

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

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

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

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

UNCOV
110
        return $data;
×
111
    }
112

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

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

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

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

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

UNCOV
148
        return $allowedAttributes;
×
149
    }
150

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

UNCOV
160
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
×
161
    }
162

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

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

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