-
-
Notifications
You must be signed in to change notification settings - Fork 963
Expand file tree
/
Copy pathHttpResponseStatusTrait.php
More file actions
60 lines (49 loc) · 2.09 KB
/
HttpResponseStatusTrait.php
File metadata and controls
60 lines (49 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\State\Util;
use ApiPlatform\Metadata\HttpOperation;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\ResourceClassResolverInterface;
use ApiPlatform\Metadata\Util\ClassInfoTrait;
use ApiPlatform\Metadata\Util\CloneTrait;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
trait HttpResponseStatusTrait
{
use ClassInfoTrait;
use CloneTrait;
private ?ResourceClassResolverInterface $resourceClassResolver;
public const METHOD_TO_CODE = [
'POST' => Response::HTTP_CREATED,
'DELETE' => Response::HTTP_NO_CONTENT,
];
/**
* @param array<string, mixed> $context
*/
private function getStatus(Request $request, HttpOperation $operation, array $context): int
{
if ($request->attributes->has('_api_response_status')) {
return $request->attributes->getInt('_api_response_status');
}
$status = $operation->getStatus();
$method = $request->getMethod();
$outputMetadata = $operation->getOutput() ?? ['class' => $operation->getClass()];
$hasOutput = \is_array($outputMetadata) && \array_key_exists('class', $outputMetadata) && null !== $outputMetadata['class'];
$originalData = $context['original_data'] ?? null;
$hasData = !$hasOutput ? false : ($this->resourceClassResolver && $originalData && \is_object($originalData) && $this->resourceClassResolver->isResourceClass($this->getObjectClass($originalData)));
if ($hasData) {
if ('PUT' === $method && !$request->attributes->get('previous_data') && null === $status && ($operation instanceof Put && ($operation->getAllowCreate() ?? false))) {
$status = Response::HTTP_CREATED;
}
}
return $status ?? self::METHOD_TO_CODE[$method] ?? Response::HTTP_OK;
}
}