|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Chubbyphp\ApiHttp\Manager; |
|
6
|
|
|
|
|
7
|
|
|
use Chubbyphp\ApiHttp\Factory\ResponseFactoryInterface; |
|
8
|
|
|
use Chubbyphp\Serialization\SerializerInterface; |
|
9
|
|
|
use Chubbyphp\Serialization\TransformerInterface; |
|
10
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
11
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
12
|
|
|
|
|
13
|
|
|
final class ResponseManager implements ResponseManagerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var RequestManagerInterface |
|
17
|
|
|
*/ |
|
18
|
|
|
private $requestManager; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var ResponseFactoryInterface |
|
22
|
|
|
*/ |
|
23
|
|
|
private $responseFactory; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var SerializerInterface |
|
27
|
|
|
*/ |
|
28
|
|
|
private $serializer; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @var TransformerInterface |
|
32
|
|
|
*/ |
|
33
|
|
|
private $transformer; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* @param RequestManagerInterface $requestManager |
|
37
|
|
|
* @param ResponseFactoryInterface $responseFactory |
|
38
|
|
|
* @param SerializerInterface $serializer |
|
39
|
|
|
* @param TransformerInterface $transformer |
|
40
|
|
|
*/ |
|
41
|
|
|
public function __construct( |
|
42
|
|
|
RequestManagerInterface $requestManager, |
|
43
|
|
|
ResponseFactoryInterface $responseFactory, |
|
44
|
|
|
SerializerInterface $serializer, |
|
45
|
|
|
TransformerInterface $transformer |
|
46
|
|
|
) { |
|
47
|
|
|
$this->requestManager = $requestManager; |
|
48
|
|
|
$this->responseFactory = $responseFactory; |
|
49
|
|
|
$this->serializer = $serializer; |
|
50
|
|
|
$this->transformer = $transformer; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param Request $request |
|
55
|
|
|
* @param int $code |
|
56
|
|
|
* @param object $object |
|
57
|
|
|
* |
|
58
|
|
|
* @return Response |
|
59
|
|
|
*/ |
|
60
|
|
|
public function createResponse(Request $request, int $code, $object = null): Response |
|
61
|
|
|
{ |
|
62
|
|
|
$response = $this->responseFactory->createResponse($code); |
|
63
|
|
|
|
|
64
|
|
|
if (null === $object) { |
|
65
|
|
|
return $response->withStatus(204); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
if (null === $accept = $this->requestManager->getAccept($request)) { |
|
69
|
|
|
return $response->withStatus(406); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
$body = $this->transformer->transform($this->serializer->serialize($request, $object), $accept); |
|
73
|
|
|
|
|
74
|
|
|
/** @var Response $response */ |
|
75
|
|
|
$response = $response->withStatus($code)->withHeader('Content-Type', $accept); |
|
76
|
|
|
$response->getBody()->write($body); |
|
77
|
|
|
|
|
78
|
|
|
return $response; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|