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

api-platform / core / 7196499749

13 Dec 2023 02:17PM UTC coverage: 37.359% (+1.4%) from 36.003%
7196499749

push

github

web-flow
ci: conflict sebastian/comparator (#6032)

* ci: conflict sebastian/comparator

* for lowest

10295 of 27557 relevant lines covered (37.36%)

28.14 hits per line

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

4.35
/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\IdentifiersExtractorInterface;
18
use ApiPlatform\Metadata\IriConverterInterface;
19
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
20
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
21
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
22
use ApiPlatform\Metadata\ResourceClassResolverInterface;
23
use ApiPlatform\Metadata\Util\ClassInfoTrait;
24
use ApiPlatform\Serializer\CacheKeyTrait;
25
use ApiPlatform\Serializer\ItemNormalizer as BaseItemNormalizer;
26
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
27
use Psr\Log\LoggerInterface;
28
use Psr\Log\NullLogger;
29
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
30
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
31
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
32
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
33

34
/**
35
 * GraphQL normalizer.
36
 *
37
 * @author Kévin Dunglas <dunglas@gmail.com>
38
 */
39
final class ItemNormalizer extends BaseItemNormalizer
40
{
41
    use CacheKeyTrait;
42
    use ClassInfoTrait;
43

44
    public const FORMAT = 'graphql';
45
    public const ITEM_RESOURCE_CLASS_KEY = '#itemResourceClass';
46
    public const ITEM_IDENTIFIERS_KEY = '#itemIdentifiers';
47

48
    private array $safeCacheKeysCache = [];
49

50
    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)
51
    {
52
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $logger ?: new NullLogger(), $resourceMetadataCollectionFactory, $resourceAccessChecker);
116✔
53
    }
54

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

63
    public function getSupportedTypes($format): array
64
    {
65
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
72✔
66
    }
67

68
    /**
69
     * {@inheritdoc}
70
     *
71
     * @param array<string, mixed> $context
72
     *
73
     * @throws UnexpectedValueException
74
     */
75
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
76
    {
77
        $resourceClass = $this->getObjectClass($object);
×
78

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

85
            return parent::normalize($object, $format, $context);
×
86
        }
87

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

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

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

105
        return $data;
×
106
    }
107

108
    /**
109
     * {@inheritdoc}
110
     */
111
    protected function normalizeCollectionOfRelations(ApiProperty $propertyMetadata, iterable $attributeValue, string $resourceClass, ?string $format, array $context): array
112
    {
113
        // to-many are handled directly by the GraphQL resolver
114
        return [];
×
115
    }
116

117
    /**
118
     * {@inheritdoc}
119
     */
120
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
121
    {
122
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
123
    }
124

125
    /**
126
     * {@inheritdoc}
127
     */
128
    protected function getAllowedAttributes(string|object $classOrObject, array $context, bool $attributesAsString = false): array|bool
129
    {
130
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
×
131

132
        if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
×
133
            $allowedAttributes[] = '_id';
×
134
            array_splice($allowedAttributes, (int) $indexId, 1);
×
135
        }
136

137
        return $allowedAttributes;
×
138
    }
139

140
    /**
141
     * {@inheritdoc}
142
     */
143
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = []): void
144
    {
145
        if ('_id' === $attribute) {
×
146
            $attribute = 'id';
×
147
        }
148

149
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
×
150
    }
151

152
    /**
153
     * Check if any property contains a security grants, which makes the cache key not safe,
154
     * as allowed_properties can differ for 2 instances of the same object.
155
     */
156
    private function isCacheKeySafe(array $context): bool
157
    {
158
        if (!isset($context['resource_class']) || !$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
×
159
            return false;
×
160
        }
161
        $resourceClass = $this->resourceClassResolver->getResourceClass(null, $context['resource_class']);
×
162
        if (isset($this->safeCacheKeysCache[$resourceClass])) {
×
163
            return $this->safeCacheKeysCache[$resourceClass];
×
164
        }
165
        $options = $this->getFactoryOptions($context);
×
166
        $propertyNames = $this->propertyNameCollectionFactory->create($resourceClass, $options);
×
167

168
        $this->safeCacheKeysCache[$resourceClass] = true;
×
169
        foreach ($propertyNames as $propertyName) {
×
170
            $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName, $options);
×
171
            if (null !== $propertyMetadata->getSecurity()) {
×
172
                $this->safeCacheKeysCache[$resourceClass] = false;
×
173
                break;
×
174
            }
175
        }
176

177
        return $this->safeCacheKeysCache[$resourceClass];
×
178
    }
179
}
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

© 2026 Coveralls, Inc