1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace N1215\SimpleAdr\Responder; |
5
|
|
|
|
6
|
|
|
use N1215\SimpleAdr\Domain\User; |
7
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
8
|
|
|
use Psr\Http\Message\StreamFactoryInterface; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* User show responder |
13
|
|
|
* @package N1215\SimpleAdr\Responder |
14
|
|
|
*/ |
15
|
|
|
class UserShowJsonResponder |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var ResponseFactoryInterface |
19
|
|
|
*/ |
20
|
|
|
private $responseFactory; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var StreamFactoryInterface |
24
|
|
|
*/ |
25
|
|
|
private $streamFactory; |
26
|
|
|
|
27
|
1 |
|
public function __construct(ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory) |
28
|
|
|
{ |
29
|
1 |
|
$this->responseFactory = $responseFactory; |
30
|
1 |
|
$this->streamFactory = $streamFactory; |
31
|
1 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param User|null $user |
35
|
|
|
* @return ResponseInterface |
36
|
|
|
*/ |
37
|
1 |
|
public function respond(User $user = null): ResponseInterface |
38
|
|
|
{ |
39
|
1 |
|
if($user === null) { |
40
|
1 |
|
return $this->createJsonResponse([ |
41
|
1 |
|
'error' => [ |
42
|
|
|
'type' => 'not_found', |
43
|
|
|
'message' => 'User not found.', |
44
|
|
|
], |
45
|
1 |
|
], 404); |
46
|
|
|
} |
47
|
|
|
|
48
|
1 |
|
return $this->createJsonResponse($user, 200); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param array|\JsonSerializable $body |
53
|
|
|
* @param int $status |
54
|
|
|
* @return ResponseInterface |
55
|
|
|
*/ |
56
|
1 |
|
private function createJsonResponse($body, int $status): ResponseInterface |
57
|
|
|
{ |
58
|
1 |
|
return $this->responseFactory |
59
|
1 |
|
->createResponse($status) |
60
|
1 |
|
->withBody($this->streamFactory->createStream(\json_encode($body))) |
61
|
1 |
|
->withHeader('content-type', 'application/json'); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|