Completed
Push — master ( a1da24...44a686 )
by Antoine
18s queued 11s
created

ItemNormalizer::normalize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 3
dl 0
loc 15
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
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\Core\GraphQl\Serializer;
15
16
use ApiPlatform\Core\Api\IdentifiersExtractorInterface;
17
use ApiPlatform\Core\Api\IriConverterInterface;
18
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
19
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
20
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
23
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
24
use ApiPlatform\Core\Serializer\ItemNormalizer as BaseItemNormalizer;
25
use ApiPlatform\Core\Util\ClassInfoTrait;
26
use Psr\Log\LoggerInterface;
27
use Psr\Log\NullLogger;
28
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
29
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
30
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
31
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
32
33
/**
34
 * GraphQL normalizer.
35
 *
36
 * @author Kévin Dunglas <[email protected]>
37
 */
38
final class ItemNormalizer extends BaseItemNormalizer
39
{
40
    use ClassInfoTrait;
41
42
    public const FORMAT = 'graphql';
43
    public const ITEM_RESOURCE_CLASS_KEY = '#itemResourceClass';
44
    public const ITEM_IDENTIFIERS_KEY = '#itemIdentifiers';
45
46
    private $identifiersExtractor;
47
48
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, IdentifiersExtractorInterface $identifiersExtractor, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, LoggerInterface $logger = null, iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null)
49
    {
50
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $itemDataProvider, $allowPlainIdentifiers, $logger ?: new NullLogger(), $dataTransformers, $resourceMetadataFactory);
51
52
        $this->identifiersExtractor = $identifiersExtractor;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function supportsNormalization($data, $format = null, array $context = []): bool
59
    {
60
        return self::FORMAT === $format && parent::supportsNormalization($data, $format, $context);
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     *
66
     * @throws UnexpectedValueException
67
     */
68
    public function normalize($object, $format = null, array $context = [])
69
    {
70
        if (null !== $outputClass = $this->getOutputClass($this->getObjectClass($object), $context)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $outputClass is dead and can be removed.
Loading history...
71
            return parent::normalize($object, $format, $context);
72
        }
73
74
        $data = parent::normalize($object, $format, $context);
75
        if (!\is_array($data)) {
76
            throw new UnexpectedValueException('Expected data to be an array');
77
        }
78
79
        $data[self::ITEM_RESOURCE_CLASS_KEY] = $this->getObjectClass($object);
80
        $data[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($object);
81
82
        return $data;
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    protected function normalizeCollectionOfRelations(PropertyMetadata $propertyMetadata, $attributeValue, string $resourceClass, ?string $format, array $context): array
89
    {
90
        // to-many are handled directly by the GraphQL resolver
91
        return [];
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public function supportsDenormalization($data, $type, $format = null, array $context = []): bool
98
    {
99
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    protected function getAllowedAttributes($classOrObject, array $context, $attributesAsString = false)
106
    {
107
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
108
109
        if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
110
            $allowedAttributes[] = '_id';
111
            array_splice($allowedAttributes, (int) $indexId, 1);
112
        }
113
114
        return $allowedAttributes;
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = []): void
121
    {
122
        if ('_id' === $attribute) {
123
            $attribute = 'id';
124
        }
125
126
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
127
    }
128
}
129