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

api-platform / core / 7407219156

04 Jan 2024 08:32AM UTC coverage: 35.357% (-1.9%) from 37.257%
7407219156

push

github

soyuka
cs: various fixes

0 of 10 new or added lines in 1 file covered. (0.0%)

425 existing lines in 27 files now uncovered.

10237 of 28953 relevant lines covered (35.36%)

27.07 hits per line

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

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

16
use ApiPlatform\Exception\InvalidArgumentException as LegacyInvalidArgumentException;
17
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
18
use ApiPlatform\Metadata\HttpOperation;
19
use ApiPlatform\Metadata\IriConverterInterface;
20
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
21
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceAccessCheckerInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\UrlGeneratorInterface;
26
use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface as LegacyResourceAccessCheckerInterface;
27
use Psr\Log\LoggerInterface;
28
use Psr\Log\NullLogger;
29
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
30
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
31
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
32
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
33

34
/**
35
 * Generic item normalizer.
36
 *
37
 * @author Kévin Dunglas <dunglas@gmail.com>
38
 */
39
class ItemNormalizer extends AbstractItemNormalizer
40
{
41
    private readonly LoggerInterface $logger;
42

43
    /**
44
     * @param LegacyResourceAccessCheckerInterface|ResourceAccessCheckerInterface $resourceAccessChecker
45
     */
46
    public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, LoggerInterface $logger = null, ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory = null, $resourceAccessChecker = null, array $defaultContext = [], protected ?TagCollectorInterface $tagCollector = null)
47
    {
48
        parent::__construct($propertyNameCollectionFactory, $propertyMetadataFactory, $iriConverter, $resourceClassResolver, $propertyAccessor, $nameConverter, $classMetadataFactory, $defaultContext, $resourceMetadataFactory, $resourceAccessChecker, $tagCollector);
116✔
49

50
        $this->logger = $logger ?: new NullLogger();
116✔
51
    }
52

53
    /**
54
     * {@inheritdoc}
55
     *
56
     * @throws NotNormalizableValueException
57
     */
58
    public function denormalize(mixed $data, string $class, string $format = null, array $context = []): mixed
59
    {
60
        // Avoid issues with proxies if we populated the object
61
        if (isset($data['id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
12✔
62
            if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
×
63
                throw new NotNormalizableValueException('Update is not allowed for this operation.');
×
64
            }
65

66
            if (isset($context['resource_class'])) {
×
67
                $this->updateObjectToPopulate($data, $context);
×
68
            } else {
69
                // See https://github.com/api-platform/core/pull/2326 to understand this message.
UNCOV
70
                $this->logger->warning('The "resource_class" key is missing from the context.', [
×
UNCOV
71
                    'context' => $context,
×
UNCOV
72
                ]);
×
73
            }
74
        }
75

76
        return parent::denormalize($data, $class, $format, $context);
12✔
77
    }
78

79
    private function updateObjectToPopulate(array $data, array &$context): void
80
    {
81
        try {
82
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri((string) $data['id'], $context + ['fetch_data' => true]);
×
83
        } catch (LegacyInvalidArgumentException|InvalidArgumentException) {
×
84
            $operation = $this->resourceMetadataCollectionFactory?->create($context['resource_class'])->getOperation();
×
85
            if (
UNCOV
86
                !$operation || (
×
UNCOV
87
                    null !== ($context['uri_variables'] ?? null)
×
88
                    && $operation instanceof HttpOperation
×
UNCOV
89
                    && \count($operation->getUriVariables() ?? []) > 1
×
90
                )
91
            ) {
UNCOV
92
                throw new InvalidArgumentException('Cannot find object to populate, use JSON-LD or specify an IRI at path "id".');
×
93
            }
UNCOV
94
            $uriVariables = $this->getContextUriVariables($data, $operation, $context);
×
UNCOV
95
            $iri = $this->iriConverter->getIriFromResource($context['resource_class'], UrlGeneratorInterface::ABS_PATH, $operation, ['uri_variables' => $uriVariables]);
×
96

UNCOV
97
            $context[self::OBJECT_TO_POPULATE] = $this->iriConverter->getResourceFromIri($iri, $context + ['fetch_data' => true]);
×
98
        }
99
    }
100

101
    private function getContextUriVariables(array $data, $operation, array $context): array
102
    {
103
        $uriVariables = $context['uri_variables'] ?? [];
×
104

105
        $operationUriVariables = $operation->getUriVariables();
×
UNCOV
106
        if ((null !== $uriVariable = array_shift($operationUriVariables)) && \count($uriVariable->getIdentifiers())) {
×
UNCOV
107
            $identifier = $uriVariable->getIdentifiers()[0];
×
UNCOV
108
            if (isset($data[$identifier])) {
×
109
                $uriVariables[$uriVariable->getParameterName()] = $data[$identifier];
×
110
            }
111
        }
112

UNCOV
113
        return $uriVariables;
×
114
    }
115
}
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