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