Completed
Push — master ( d0bde7...345612 )
by Antoine
26s queued 11s
created

ItemNormalizer::normalize()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nc 5
nop 3
dl 0
loc 24
rs 8.8333
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, $allowUnmappedClass = false)
49
    {
50
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $itemDataProvider, $allowPlainIdentifiers, $logger ?: new NullLogger(), $dataTransformers, $resourceMetadataFactory, $allowUnmappedClass);
51
52
        $this->identifiersExtractor = $identifiersExtractor;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function supportsNormalization($data, $format = null, array $context = [])
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 (!$this->handleNonResource && 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
        if ($this->handleNonResource) {
80
            // when using an output class, get the IRI from the resource
81
            if (isset($context['api_resource']) && isset($data['id'])) {
82
                $data['_id'] = $data['id'];
83
                $data['id'] = $this->iriConverter->getIriFromItem($context['api_resource']);
84
                unset($context['api_resource']);
85
            }
86
        }
87
88
        $data[self::ITEM_RESOURCE_CLASS_KEY] = $this->getObjectClass($object);
89
        $data[self::ITEM_IDENTIFIERS_KEY] = $this->identifiersExtractor->getIdentifiersFromItem($object);
90
91
        return $data;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    protected function normalizeCollectionOfRelations(PropertyMetadata $propertyMetadata, $attributeValue, string $resourceClass, ?string $format, array $context): array
98
    {
99
        // to-many are handled directly by the GraphQL resolver
100
        return [];
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function supportsDenormalization($data, $type, $format = null, array $context = [])
107
    {
108
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
109
    }
110
111
    /**
112
     * {@inheritdoc}
113
     */
114
    protected function getAllowedAttributes($classOrObject, array $context, $attributesAsString = false)
115
    {
116
        $allowedAttributes = parent::getAllowedAttributes($classOrObject, $context, $attributesAsString);
117
118
        if (($context['api_denormalize'] ?? false) && \is_array($allowedAttributes) && false !== ($indexId = array_search('id', $allowedAttributes, true))) {
119
            $allowedAttributes[] = '_id';
120
            array_splice($allowedAttributes, (int) $indexId, 1);
121
        }
122
123
        return $allowedAttributes;
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
130
    {
131
        if ('_id' === $attribute) {
132
            $attribute = 'id';
133
        }
134
135
        parent::setAttributeValue($object, $attribute, $value, $format, $context);
136
    }
137
}
138