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

api-platform / core / 6067528200

04 Sep 2023 12:12AM UTC coverage: 36.875% (-21.9%) from 58.794%
6067528200

Pull #5791

github

web-flow
Merge 64157e578 into d09cfc9d2
Pull Request #5791: fix: strip down any sql function name

3096 of 3096 new or added lines in 205 files covered. (100.0%)

9926 of 26918 relevant lines covered (36.87%)

6.5 hits per line

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

47.43
/src/JsonApi/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\JsonApi\Serializer;
15

16
use ApiPlatform\Api\IriConverterInterface;
17
use ApiPlatform\Api\ResourceClassResolverInterface;
18
use ApiPlatform\Api\UrlGeneratorInterface;
19
use ApiPlatform\Exception\ItemNotFoundException;
20
use ApiPlatform\Metadata\ApiProperty;
21
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
22
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\Util\ClassInfoTrait;
25
use ApiPlatform\Serializer\AbstractItemNormalizer;
26
use ApiPlatform\Serializer\CacheKeyTrait;
27
use ApiPlatform\Serializer\ContextTrait;
28
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
29
use Symfony\Component\ErrorHandler\Exception\FlattenException;
30
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
31
use Symfony\Component\Serializer\Exception\LogicException;
32
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
33
use Symfony\Component\Serializer\Exception\RuntimeException;
34
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
35
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
36
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
37
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
38

39
/**
40
 * Converts between objects and array.
41
 *
42
 * @author Kévin Dunglas <dunglas@gmail.com>
43
 * @author Amrouche Hamza <hamza.simperfit@gmail.com>
44
 * @author Baptiste Meyer <baptiste.meyer@gmail.com>
45
 */
46
final class ItemNormalizer extends AbstractItemNormalizer
47
{
48
    use CacheKeyTrait;
49
    use ClassInfoTrait;
50
    use ContextTrait;
51

52
    public const FORMAT = 'jsonapi';
53

54
    private array $componentsCache = [];
55

56
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, array $defaultContext = [], ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null)
57
    {
58
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataCollectionFactory, $resourceAccessChecker);
105✔
59
    }
60

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

69
    public function getSupportedTypes($format): array
70
    {
71
        return self::FORMAT === $format ? parent::getSupportedTypes($format) : [];
51✔
72
    }
73

74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
78
    {
79
        $resourceClass = $this->getObjectClass($object);
9✔
80
        if ($this->getOutputClass($context)) {
9✔
81
            return parent::normalize($object, $format, $context);
×
82
        }
83

84
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
9✔
85
            $resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
9✔
86
        }
87

88
        if (($operation = $context['operation'] ?? null) && method_exists($operation, 'getItemUriTemplate')) {
9✔
89
            $context['item_uri_template'] = $operation->getItemUriTemplate();
×
90
        }
91

92
        $context = $this->initContext($resourceClass, $context);
9✔
93
        $iri = $this->iriConverter->getIriFromResource($object, UrlGeneratorInterface::ABS_PATH, $context['operation'] ?? null, $context);
9✔
94
        $context['iri'] = $iri;
9✔
95
        $context['api_normalize'] = true;
9✔
96

97
        if (!isset($context['cache_key'])) {
9✔
98
            $context['cache_key'] = $this->getCacheKey($format, $context);
9✔
99
        }
100

101
        $data = parent::normalize($object, $format, $context);
9✔
102
        if (!\is_array($data)) {
6✔
103
            return $data;
3✔
104
        }
105

106
        // Get and populate relations
107
        $allRelationshipsData = $this->getComponents($object, $format, $context)['relationships'];
3✔
108
        $populatedRelationContext = $context;
3✔
109
        $relationshipsData = $this->getPopulatedRelations($object, $format, $populatedRelationContext, $allRelationshipsData);
3✔
110

111
        // Do not include primary resources
112
        $context['api_included_resources'] = [$context['iri']];
3✔
113

114
        $includedResourcesData = $this->getRelatedResources($object, $format, $context, $allRelationshipsData);
3✔
115

116
        $resourceData = [
3✔
117
            'id' => $context['iri'],
3✔
118
            'type' => $this->getResourceShortName($resourceClass),
3✔
119
        ];
3✔
120

121
        if ($data) {
3✔
122
            $resourceData['attributes'] = $data;
3✔
123
        }
124

125
        if ($relationshipsData) {
3✔
126
            $resourceData['relationships'] = $relationshipsData;
×
127
        }
128

129
        $document = ['data' => $resourceData];
3✔
130

131
        if ($includedResourcesData) {
3✔
132
            $document['included'] = $includedResourcesData;
×
133
        }
134

135
        return $document;
3✔
136
    }
137

138
    /**
139
     * {@inheritdoc}
140
     */
141
    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
142
    {
143
        return self::FORMAT === $format && parent::supportsDenormalization($data, $type, $format, $context);
×
144
    }
145

146
    /**
147
     * {@inheritdoc}
148
     *
149
     * @throws NotNormalizableValueException
150
     */
151
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
152
    {
153
        // Avoid issues with proxies if we populated the object
154
        if (!isset($context[self::OBJECT_TO_POPULATE]) && isset($data['data']['id'])) {
15✔
155
            if (true !== ($context['api_allow_update'] ?? true)) {
3✔
156
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
3✔
157
            }
158

159
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri(
×
160
                $data['data']['id'],
×
161
                $context + ['fetch_data' => false]
×
162
            );
×
163
        }
164

165
        // Merge attributes and relationships, into format expected by the parent normalizer
166
        $dataToDenormalize = array_merge(
12✔
167
            $data['data']['attributes'] ?? [],
12✔
168
            $data['data']['relationships'] ?? []
12✔
169
        );
12✔
170

171
        return parent::denormalize(
12✔
172
            $dataToDenormalize,
12✔
173
            $class,
12✔
174
            $format,
12✔
175
            $context
12✔
176
        );
12✔
177
    }
178

179
    /**
180
     * {@inheritdoc}
181
     */
182
    protected function getAttributes(object $object, string $format = null, array $context = []): array
183
    {
184
        return $this->getComponents($object, $format, $context)['attributes'];
6✔
185
    }
186

187
    /**
188
     * {@inheritdoc}
189
     */
190
    protected function setAttributeValue(object $object, string $attribute, mixed $value, string $format = null, array $context = []): void
191
    {
192
        parent::setAttributeValue($object, $attribute, \is_array($value) && \array_key_exists('data', $value) ? $value['data'] : $value, $format, $context);
12✔
193
    }
194

195
    /**
196
     * {@inheritdoc}
197
     *
198
     * @see http://jsonapi.org/format/#document-resource-object-linkage
199
     *
200
     * @throws RuntimeException
201
     * @throws UnexpectedValueException
202
     */
203
    protected function denormalizeRelation(string $attributeName, ApiProperty $propertyMetadata, string $className, mixed $value, ?string $format, array $context): object
204
    {
205
        if (!\is_array($value) || !isset($value['id'], $value['type'])) {
6✔
206
            throw new UnexpectedValueException('Only resource linkage supported currently, see: http://jsonapi.org/format/#document-resource-object-linkage.');
3✔
207
        }
208

209
        try {
210
            return $this->iriConverter->getResourceFromIri($value['id'], $context + ['fetch_data' => true]);
3✔
211
        } catch (ItemNotFoundException $e) {
×
212
            throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
×
213
        }
214
    }
215

216
    /**
217
     * {@inheritdoc}
218
     *
219
     * @see http://jsonapi.org/format/#document-resource-object-linkage
220
     */
221
    protected function normalizeRelation(ApiProperty $propertyMetadata, ?object $relatedObject, string $resourceClass, ?string $format, array $context): \ArrayObject|array|string|null
222
    {
223
        if (null !== $relatedObject) {
×
224
            $iri = $this->iriConverter->getIriFromResource($relatedObject);
×
225
            $context['iri'] = $iri;
×
226

227
            if (isset($context['resources'])) {
×
228
                $context['resources'][$iri] = $iri;
×
229
            }
230
        }
231

232
        if (null === $relatedObject || isset($context['api_included'])) {
×
233
            if (!$this->serializer instanceof NormalizerInterface) {
×
234
                throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
×
235
            }
236

237
            $normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
×
238
            if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
×
239
                throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
×
240
            }
241

242
            return $normalizedRelatedObject;
×
243
        }
244

245
        return [
×
246
            'data' => [
×
247
                'type' => $this->getResourceShortName($resourceClass),
×
248
                'id' => $iri,
×
249
            ],
×
250
        ];
×
251
    }
252

253
    /**
254
     * {@inheritdoc}
255
     */
256
    protected function isAllowedAttribute(object|string $classOrObject, string $attribute, string $format = null, array $context = []): bool
257
    {
258
        return preg_match('/^\\w[-\\w_]*$/', $attribute) && parent::isAllowedAttribute($classOrObject, $attribute, $format, $context);
18✔
259
    }
260

261
    /**
262
     * Gets JSON API components of the resource: attributes, relationships, meta and links.
263
     */
264
    private function getComponents(object $object, ?string $format, array $context): array
265
    {
266
        $cacheKey = $this->getObjectClass($object).'-'.$context['cache_key'];
6✔
267

268
        if (isset($this->componentsCache[$cacheKey])) {
6✔
269
            return $this->componentsCache[$cacheKey];
3✔
270
        }
271

272
        $attributes = parent::getAttributes($object, $format, $context);
6✔
273

274
        $options = $this->getFactoryOptions($context);
6✔
275

276
        $components = [
6✔
277
            'links' => [],
6✔
278
            'relationships' => [],
6✔
279
            'attributes' => [],
6✔
280
            'meta' => [],
6✔
281
        ];
6✔
282

283
        foreach ($attributes as $attribute) {
6✔
284
            $propertyMetadata = $this
6✔
285
                ->propertyMetadataFactory
6✔
286
                ->create($context['resource_class'], $attribute, $options);
6✔
287

288
            $types = $propertyMetadata->getBuiltinTypes() ?? [];
6✔
289

290
            // prevent declaring $attribute as attribute if it's already declared as relationship
291
            $isRelationship = false;
6✔
292

293
            foreach ($types as $type) {
6✔
294
                $isOne = $isMany = false;
×
295

296
                if ($type->isCollection()) {
×
297
                    $collectionValueType = $type->getCollectionValueTypes()[0] ?? null;
×
298
                    $isMany = $collectionValueType && ($className = $collectionValueType->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
299
                } else {
300
                    $isOne = ($className = $type->getClassName()) && $this->resourceClassResolver->isResourceClass($className);
×
301
                }
302

303
                if (!isset($className) || !$isOne && !$isMany) {
×
304
                    // don't declare it as an attribute too quick: maybe the next type is a valid resource
305
                    continue;
×
306
                }
307

308
                $relation = [
×
309
                    'name' => $attribute,
×
310
                    'type' => $this->getResourceShortName($className),
×
311
                    'cardinality' => $isOne ? 'one' : 'many',
×
312
                ];
×
313

314
                $components['relationships'][] = $relation;
×
315
                $isRelationship = true;
×
316
            }
317

318
            // if all types are not relationships, declare it as an attribute
319
            if (!$isRelationship) {
6✔
320
                $components['attributes'][] = $attribute;
6✔
321
            }
322
        }
323

324
        if (false !== $context['cache_key']) {
6✔
325
            $this->componentsCache[$cacheKey] = $components;
6✔
326
        }
327

328
        return $components;
6✔
329
    }
330

331
    /**
332
     * Populates relationships keys.
333
     *
334
     * @throws UnexpectedValueException
335
     */
336
    private function getPopulatedRelations(object $object, ?string $format, array $context, array $relationships): array
337
    {
338
        $data = [];
3✔
339

340
        if (!isset($context['resource_class'])) {
3✔
341
            return $data;
×
342
        }
343

344
        unset($context['api_included']);
3✔
345
        foreach ($relationships as $relationshipDataArray) {
3✔
346
            $relationshipName = $relationshipDataArray['name'];
×
347

348
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $context);
×
349

350
            if ($this->nameConverter) {
×
351
                $relationshipName = $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context);
×
352
            }
353

354
            if (!$attributeValue) {
×
355
                continue;
×
356
            }
357

358
            $data[$relationshipName] = [
×
359
                'data' => [],
×
360
            ];
×
361

362
            // Many to one relationship
363
            if ('one' === $relationshipDataArray['cardinality']) {
×
364
                unset($attributeValue['data']['attributes']);
×
365
                $data[$relationshipName] = $attributeValue;
×
366

367
                continue;
×
368
            }
369

370
            // Many to many relationship
371
            foreach ($attributeValue as $attributeValueElement) {
×
372
                if (!isset($attributeValueElement['data'])) {
×
373
                    throw new UnexpectedValueException(sprintf('The JSON API attribute \'%s\' must contain a "data" key.', $relationshipName));
×
374
                }
375
                unset($attributeValueElement['data']['attributes']);
×
376
                $data[$relationshipName]['data'][] = $attributeValueElement['data'];
×
377
            }
378
        }
379

380
        return $data;
3✔
381
    }
382

383
    /**
384
     * Populates included keys.
385
     */
386
    private function getRelatedResources(object $object, ?string $format, array $context, array $relationships): array
387
    {
388
        if (!isset($context['api_included'])) {
3✔
389
            return [];
3✔
390
        }
391

392
        $included = [];
×
393
        foreach ($relationships as $relationshipDataArray) {
×
394
            $relationshipName = $relationshipDataArray['name'];
×
395

396
            if (!$this->shouldIncludeRelation($relationshipName, $context)) {
×
397
                continue;
×
398
            }
399

400
            $relationContext = $context;
×
401
            $relationContext['api_included'] = $this->getIncludedNestedResources($relationshipName, $context);
×
402

403
            $attributeValue = $this->getAttributeValue($object, $relationshipName, $format, $relationContext);
×
404

405
            if (!$attributeValue) {
×
406
                continue;
×
407
            }
408

409
            // Many to many relationship
410
            $attributeValues = $attributeValue;
×
411
            // Many to one relationship
412
            if ('one' === $relationshipDataArray['cardinality']) {
×
413
                $attributeValues = [$attributeValue];
×
414
            }
415

416
            foreach ($attributeValues as $attributeValueElement) {
×
417
                if (isset($attributeValueElement['data'])) {
×
418
                    $this->addIncluded($attributeValueElement['data'], $included, $context);
×
419
                    if (isset($attributeValueElement['included']) && \is_array($attributeValueElement['included'])) {
×
420
                        foreach ($attributeValueElement['included'] as $include) {
×
421
                            $this->addIncluded($include, $included, $context);
×
422
                        }
423
                    }
424
                }
425
            }
426
        }
427

428
        return $included;
×
429
    }
430

431
    /**
432
     * Add data to included array if it's not already included.
433
     */
434
    private function addIncluded(array $data, array &$included, array &$context): void
435
    {
436
        if (isset($data['id']) && !\in_array($data['id'], $context['api_included_resources'], true)) {
×
437
            $included[] = $data;
×
438
            // Track already included resources
439
            $context['api_included_resources'][] = $data['id'];
×
440
        }
441
    }
442

443
    /**
444
     * Figures out if the relationship is in the api_included hash or has included nested resources (path).
445
     */
446
    private function shouldIncludeRelation(string $relationshipName, array $context): bool
447
    {
448
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
449

450
        return \in_array($normalizedName, $context['api_included'], true) || \count($this->getIncludedNestedResources($relationshipName, $context)) > 0;
×
451
    }
452

453
    /**
454
     * Returns the names of the nested resources from a path relationship.
455
     */
456
    private function getIncludedNestedResources(string $relationshipName, array $context): array
457
    {
458
        $normalizedName = $this->nameConverter ? $this->nameConverter->normalize($relationshipName, $context['resource_class'], self::FORMAT, $context) : $relationshipName;
×
459

460
        $filtered = array_filter($context['api_included'] ?? [], static fn (string $included): bool => str_starts_with($included, $normalizedName.'.'));
×
461

462
        return array_map(static fn (string $nested): string => substr($nested, strpos($nested, '.') + 1), $filtered);
×
463
    }
464

465
    // TODO: this code is similar to the one used in JsonLd
466
    private function getResourceShortName(string $resourceClass): string
467
    {
468
        if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
3✔
469
            $resourceMetadata = $this->resourceMetadataCollectionFactory->create($resourceClass);
3✔
470

471
            return $resourceMetadata->getOperation()->getShortName();
3✔
472
        }
473

474
        return (new \ReflectionClass($resourceClass))->getShortName();
×
475
    }
476
}
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