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

api-platform / core / 10957611709

20 Sep 2024 10:27AM UTC coverage: 7.372% (-0.3%) from 7.647%
10957611709

push

github

dunglas
Merge branch '4.0'

25 of 40 new or added lines in 9 files covered. (62.5%)

111 existing lines in 4 files now uncovered.

12175 of 165159 relevant lines covered (7.37%)

22.96 hits per line

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

96.67
/src/State/Processor/RespondProcessor.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\State\Processor;
15

16
use ApiPlatform\Metadata\Exception\HttpExceptionInterface;
17
use ApiPlatform\Metadata\Exception\InvalidArgumentException;
18
use ApiPlatform\Metadata\Exception\ItemNotFoundException;
19
use ApiPlatform\Metadata\Exception\RuntimeException;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\IriConverterInterface;
22
use ApiPlatform\Metadata\Operation;
23
use ApiPlatform\Metadata\Operation\Factory\OperationMetadataFactoryInterface;
24
use ApiPlatform\Metadata\Put;
25
use ApiPlatform\Metadata\ResourceClassResolverInterface;
26
use ApiPlatform\Metadata\UrlGeneratorInterface;
27
use ApiPlatform\Metadata\Util\ClassInfoTrait;
28
use ApiPlatform\Metadata\Util\CloneTrait;
29
use ApiPlatform\State\ProcessorInterface;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
32

33
/**
34
 * Serializes data.
35
 *
36
 * @author Kévin Dunglas <dunglas@gmail.com>
37
 */
38
final class RespondProcessor implements ProcessorInterface
39
{
40
    use ClassInfoTrait;
41
    use CloneTrait;
42

43
    public const METHOD_TO_CODE = [
44
        'POST' => Response::HTTP_CREATED,
45
        'DELETE' => Response::HTTP_NO_CONTENT,
46
    ];
47

48
    public function __construct(
49
        private ?IriConverterInterface $iriConverter = null,
50
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
51
        private readonly ?OperationMetadataFactoryInterface $operationMetadataFactory = null,
52
    ) {
53
    }
1,854✔
54

55
    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = [])
56
    {
57
        if ($data instanceof Response || !$operation instanceof HttpOperation) {
1,842✔
58
            return $data;
19✔
59
        }
60

61
        if (!($request = $context['request'] ?? null)) {
1,823✔
62
            return $data;
×
63
        }
64

65
        $headers = [
1,823✔
66
            'Content-Type' => \sprintf('%s; charset=utf-8', $request->getMimeType($request->getRequestFormat())),
1,823✔
67
            'Vary' => 'Accept',
1,823✔
68
            'X-Content-Type-Options' => 'nosniff',
1,823✔
69
            'X-Frame-Options' => 'deny',
1,823✔
70
        ];
1,823✔
71

72
        $exception = $request->attributes->get('exception');
1,823✔
73
        if (($exception instanceof HttpExceptionInterface || $exception instanceof SymfonyHttpExceptionInterface) && $exceptionHeaders = $exception->getHeaders()) {
1,823✔
74
            $headers = array_merge($headers, $exceptionHeaders);
2✔
75
        }
76

77
        if ($operationHeaders = $operation->getHeaders()) {
1,823✔
78
            $headers = array_merge($headers, $operationHeaders);
3✔
79
        }
80

81
        $status = $operation->getStatus();
1,823✔
82

83
        if ($sunset = $operation->getSunset()) {
1,823✔
84
            $headers['Sunset'] = (new \DateTimeImmutable($sunset))->format(\DateTimeInterface::RFC1123);
6✔
85
        }
86

87
        if ($acceptPatch = $operation->getAcceptPatch()) {
1,823✔
88
            $headers['Accept-Patch'] = $acceptPatch;
535✔
89
        }
90

91
        $method = $request->getMethod();
1,823✔
92
        $originalData = $context['original_data'] ?? null;
1,823✔
93

94
        $outputMetadata = $operation->getOutput() ?? ['class' => $operation->getClass()];
1,823✔
95
        $hasOutput = \is_array($outputMetadata) && \array_key_exists('class', $outputMetadata) && null !== $outputMetadata['class'];
1,823✔
96
        $hasData = !$hasOutput ? false : ($this->resourceClassResolver && $originalData && \is_object($originalData) && $this->resourceClassResolver->isResourceClass($this->getObjectClass($originalData)));
1,823✔
97

98
        if ($hasData) {
1,823✔
99
            $isAlternateResourceMetadata = $operation->getExtraProperties()['is_alternate_resource_metadata'] ?? false;
999✔
100
            $canonicalUriTemplate = $operation->getExtraProperties()['canonical_uri_template'] ?? null;
999✔
101

102
            if (
103
                !isset($headers['Location'])
999✔
104
                && 300 <= $status && $status < 400
999✔
105
                && ($isAlternateResourceMetadata || $canonicalUriTemplate)
999✔
106
            ) {
107
                $canonicalOperation = $operation;
2✔
NEW
108
                if ($this->operationMetadataFactory && null !== $canonicalUriTemplate) {
2✔
NEW
109
                    $canonicalOperation = $this->operationMetadataFactory->create($canonicalUriTemplate, $context);
×
110
                }
111

NEW
112
                if ($this->iriConverter) {
2✔
NEW
113
                    $headers['Location'] = $this->iriConverter->getIriFromResource($originalData, UrlGeneratorInterface::ABS_PATH, $canonicalOperation);
2✔
114
                }
115
            } elseif ('PUT' === $method && !$request->attributes->get('previous_data') && null === $status && ($operation instanceof Put && ($operation->getAllowCreate() ?? false))) {
997✔
116
                $status = 201;
7✔
117
            }
118
        }
119

120
        $status ??= self::METHOD_TO_CODE[$method] ?? 200;
1,823✔
121

122
        $requestParts = parse_url($request->getRequestUri());
1,823✔
123
        if ($this->iriConverter && !isset($headers['Content-Location'])) {
1,823✔
124
            try {
125
                $iri = null;
1,823✔
126
                if ($hasData) {
1,823✔
127
                    $iri = $this->iriConverter->getIriFromResource($originalData);
999✔
128
                } elseif ($operation->getClass()) {
863✔
129
                    $iri = $this->iriConverter->getIriFromResource($operation->getClass(), UrlGeneratorInterface::ABS_PATH, $operation);
845✔
130
                }
131

132
                if ($iri) {
1,711✔
133
                    $location = \sprintf('%s.%s', $iri, $request->getRequestFormat());
1,693✔
134
                    if (isset($requestParts['query'])) {
1,693✔
135
                        $location .= '?'.$requestParts['query'];
573✔
136
                    }
137

138
                    $headers['Content-Location'] = $location;
1,693✔
139
                    if ((201 === $status || (300 <= $status && $status < 400)) && 'POST' === $method && !isset($headers['Location'])) {
1,693✔
140
                        $headers['Location'] = $iri;
1,711✔
141
                    }
142
                }
143
            } catch (InvalidArgumentException|ItemNotFoundException|RuntimeException) {
115✔
144
            }
145
        }
146

147
        return new Response(
1,823✔
148
            $data,
1,823✔
149
            $status,
1,823✔
150
            $headers
1,823✔
151
        );
1,823✔
152
    }
153
}
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