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

api-platform / core / 14246153067

03 Apr 2025 02:56PM UTC coverage: 7.286% (-0.002%) from 7.288%
14246153067

push

github

web-flow
Merge commit from fork

12 of 160 new or added lines in 7 files covered. (7.5%)

2343 existing lines in 152 files now uncovered.

12450 of 170870 relevant lines covered (7.29%)

12.06 hits per line

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

98.33
/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
    }
931✔
54

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

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

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

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

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

81
        $status = $operation->getStatus();
905✔
82

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

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

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

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

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

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

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

120
        $status ??= self::METHOD_TO_CODE[$method] ?? 200;
905✔
121

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

132
                if ($iri && 'GET' !== $method) {
850✔
133
                    $location = \sprintf('%s.%s', $iri, $request->getRequestFormat());
156✔
134
                    if (isset($requestParts['query'])) {
156✔
UNCOV
135
                        $location .= '?'.$requestParts['query'];
12✔
136
                    }
137

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

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