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

api-platform / core / 13203378522

07 Feb 2025 03:56PM UTC coverage: 8.501% (+0.7%) from 7.837%
13203378522

push

github

soyuka
Merge 4.1

111 of 490 new or added lines in 51 files covered. (22.65%)

5590 existing lines in 163 files now uncovered.

13345 of 156987 relevant lines covered (8.5%)

22.88 hits per line

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

93.44
/src/Metadata/Property/Factory/SerializerPropertyMetadataFactory.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\Metadata\Property\Factory;
15

16
use ApiPlatform\Metadata\ApiProperty;
17
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
18
use ApiPlatform\Metadata\ResourceClassResolverInterface;
19
use ApiPlatform\Metadata\Util\ResourceClassInfoTrait;
20
use Symfony\Component\Serializer\Mapping\AttributeMetadataInterface;
21
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface as SerializerClassMetadataFactoryInterface;
22

23
/**
24
 * Populates read/write and link status using serialization groups.
25
 *
26
 * @author Kévin Dunglas <dunglas@gmail.com>
27
 * @author Teoh Han Hui <teohhanhui@gmail.com>
28
 */
29
final class SerializerPropertyMetadataFactory implements PropertyMetadataFactoryInterface
30
{
31
    use ResourceClassInfoTrait;
32

33
    public function __construct(private readonly SerializerClassMetadataFactoryInterface $serializerClassMetadataFactory, private readonly PropertyMetadataFactoryInterface $decorated, ?ResourceClassResolverInterface $resourceClassResolver = null)
34
    {
35
        $this->resourceClassResolver = $resourceClassResolver;
2,049✔
36
    }
37

38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function create(string $resourceClass, string $property, array $options = []): ApiProperty
42
    {
43
        $propertyMetadata = $this->decorated->create($resourceClass, $property, $options);
512✔
44

45
        try {
46
            [$normalizationGroups, $denormalizationGroups] = $this->getEffectiveSerializerGroups($options);
512✔
47

48
            if ($normalizationGroups && !\is_array($normalizationGroups)) {
512✔
49
                $normalizationGroups = [$normalizationGroups];
×
50
            }
51

52
            if ($denormalizationGroups && !\is_array($denormalizationGroups)) {
512✔
53
                $denormalizationGroups = [$denormalizationGroups];
×
54
            }
55

56
            $ignoredAttributes = $options['ignored_attributes'] ?? [];
512✔
UNCOV
57
        } catch (ResourceClassNotFoundException) {
×
58
            // TODO: for input/output classes, the serializer groups must be read from the actual resource class
59
            return $propertyMetadata;
×
60
        }
61

62
        $propertyMetadata = $this->transformReadWrite($propertyMetadata, $resourceClass, $property, $normalizationGroups, $denormalizationGroups, $ignoredAttributes);
512✔
63
        $types = $propertyMetadata->getBuiltinTypes() ?? [];
512✔
64

65
        if (!$this->isResourceClass($resourceClass) && $types) {
512✔
66
            foreach ($types as $builtinType) {
92✔
67
                if ($builtinType->isCollection()) {
92✔
68
                    return $propertyMetadata->withReadableLink(true)->withWritableLink(true);
24✔
69
                }
70
            }
71
        }
72

73
        return $this->transformLinkStatus($propertyMetadata, $normalizationGroups, $denormalizationGroups, $types);
512✔
74
    }
75

76
    /**
77
     * Sets readable/writable based on matching normalization/denormalization groups and property's ignorance.
78
     *
79
     * A false value is never reset as it could be unreadable/unwritable for other reasons.
80
     * If normalization/denormalization groups are not specified and the property is not ignored, the property is implicitly readable/writable.
81
     *
82
     * @param string[]|null $normalizationGroups
83
     * @param string[]|null $denormalizationGroups
84
     */
85
    private function transformReadWrite(ApiProperty $propertyMetadata, string $resourceClass, string $propertyName, ?array $normalizationGroups = null, ?array $denormalizationGroups = null, array $ignoredAttributes = []): ApiProperty
86
    {
87
        if (\in_array($propertyName, $ignoredAttributes, true)) {
512✔
88
            return $propertyMetadata->withWritable(false)->withReadable(false);
6✔
89
        }
90

91
        $serializerAttributeMetadata = $this->getSerializerAttributeMetadata($resourceClass, $propertyName);
512✔
92
        $groups = $serializerAttributeMetadata ? $serializerAttributeMetadata->getGroups() : [];
512✔
93
        $ignored = $serializerAttributeMetadata && $serializerAttributeMetadata->isIgnored();
512✔
94

95
        if (false !== $propertyMetadata->isReadable()) {
512✔
96
            $propertyMetadata = $propertyMetadata->withReadable(!$ignored && (null === $normalizationGroups || array_intersect($normalizationGroups, $groups)));
500✔
97
        }
98

99
        if (false !== $propertyMetadata->isWritable()) {
512✔
100
            $propertyMetadata = $propertyMetadata->withWritable(!$ignored && (null === $denormalizationGroups || array_intersect($denormalizationGroups, $groups)));
457✔
101
        }
102

103
        return $propertyMetadata;
512✔
104
    }
105

106
    /**
107
     * Sets readableLink/writableLink based on matching normalization/denormalization groups.
108
     *
109
     * If normalization/denormalization groups are not specified,
110
     * set link status to false since embedding of resource must be explicitly enabled
111
     *
112
     * @param string[]|null $normalizationGroups
113
     * @param string[]|null $denormalizationGroups
114
     */
115
    private function transformLinkStatus(ApiProperty $propertyMetadata, ?array $normalizationGroups = null, ?array $denormalizationGroups = null, ?array $types = null): ApiProperty
116
    {
117
        // No need to check link status if property is not readable and not writable
118
        if (false === $propertyMetadata->isReadable() && false === $propertyMetadata->isWritable()) {
512✔
119
            return $propertyMetadata;
125✔
120
        }
121

122
        foreach ($types as $type) {
480✔
123
            if (
124
                $type->isCollection()
464✔
125
                && $collectionValueType = $type->getCollectionValueTypes()[0] ?? null
464✔
126
            ) {
127
                $relatedClass = $collectionValueType->getClassName();
116✔
128
            } else {
129
                $relatedClass = $type->getClassName();
464✔
130
            }
131

132
            // if property is not a resource relation, don't set link status (as it would have no meaning)
133
            if (null === $relatedClass || !$this->isResourceClass($relatedClass)) {
464✔
134
                continue;
455✔
135
            }
136

137
            // find the resource class
138
            // this prevents serializer groups on non-resource child class from incorrectly influencing the decision
139
            if (null !== $this->resourceClassResolver) {
182✔
140
                $relatedClass = $this->resourceClassResolver->getResourceClass(null, $relatedClass);
182✔
141
            }
142

143
            $relatedGroups = $this->getClassSerializerGroups($relatedClass);
182✔
144

145
            if (null === $propertyMetadata->isReadableLink()) {
182✔
146
                $propertyMetadata = $propertyMetadata->withReadableLink(null !== $normalizationGroups && !empty(array_intersect($normalizationGroups, $relatedGroups)));
182✔
147
            }
148

149
            if (null === $propertyMetadata->isWritableLink()) {
182✔
150
                $propertyMetadata = $propertyMetadata->withWritableLink(null !== $denormalizationGroups && !empty(array_intersect($denormalizationGroups, $relatedGroups)));
182✔
151
            }
152

153
            return $propertyMetadata;
182✔
154
        }
155

156
        return $propertyMetadata;
471✔
157
    }
158

159
    /**
160
     * Gets the effective serializer groups used in normalization/denormalization.
161
     *
162
     * Groups are extracted in the following order:
163
     *
164
     * - From the "serializer_groups" key of the $options array.
165
     * - From metadata of the given operation ("operation_name" key).
166
     * - From metadata of the current resource.
167
     *
168
     * @return (string[]|string|null)[]
169
     */
170
    private function getEffectiveSerializerGroups(array $options): array
171
    {
172
        if (isset($options['serializer_groups'])) {
512✔
173
            $groups = (array) $options['serializer_groups'];
194✔
174

175
            return [$groups, $groups];
194✔
176
        }
177

178
        if (\array_key_exists('normalization_groups', $options) && \array_key_exists('denormalization_groups', $options)) {
355✔
179
            return [$options['normalization_groups'] ?? null, $options['denormalization_groups'] ?? null];
258✔
180
        }
181

182
        return [null, null];
170✔
183
    }
184

185
    private function getSerializerAttributeMetadata(string $class, string $attribute): ?AttributeMetadataInterface
186
    {
187
        $serializerClassMetadata = $this->serializerClassMetadataFactory->getMetadataFor($class);
512✔
188

189
        foreach ($serializerClassMetadata->getAttributesMetadata() as $serializerAttributeMetadata) {
512✔
190
            if ($attribute === $serializerAttributeMetadata->getName()) {
511✔
191
                return $serializerAttributeMetadata;
500✔
192
            }
193
        }
194

195
        return null;
33✔
196
    }
197

198
    /**
199
     * Gets all serializer groups used in a class.
200
     *
201
     * @return string[]
202
     */
203
    private function getClassSerializerGroups(string $class): array
204
    {
205
        $serializerClassMetadata = $this->serializerClassMetadataFactory->getMetadataFor($class);
182✔
206

207
        $groups = [];
182✔
208
        foreach ($serializerClassMetadata->getAttributesMetadata() as $serializerAttributeMetadata) {
182✔
209
            $groups[] = $serializerAttributeMetadata->getGroups();
182✔
210
        }
211

212
        return array_unique(array_merge(...$groups));
182✔
213
    }
214
}
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