-
Notifications
You must be signed in to change notification settings - Fork 2
/
UserShowJsonResponder.php
68 lines (60 loc) · 1.72 KB
/
UserShowJsonResponder.php
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
61
62
63
64
65
66
67
68
<?php
declare(strict_types=1);
namespace N1215\SimpleAdr\Responder;
use JsonSerializable;
use N1215\SimpleAdr\Domain\User;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\ResponseInterface;
/**
* User show responder
* @package N1215\SimpleAdr\Responder
*/
class UserShowJsonResponder
{
/**
* @var ResponseFactoryInterface
*/
private $responseFactory;
/**
* @var StreamFactoryInterface
*/
private $streamFactory;
/**
* @param ResponseFactoryInterface $responseFactory
* @param StreamFactoryInterface $streamFactory
*/
public function __construct(ResponseFactoryInterface $responseFactory, StreamFactoryInterface $streamFactory)
{
$this->responseFactory = $responseFactory;
$this->streamFactory = $streamFactory;
}
/**
* @param User|null $user
* @return ResponseInterface
*/
public function respond(User $user = null): ResponseInterface
{
if ($user === null) {
return $this->createJsonResponse([
'error' => [
'type' => 'not_found',
'message' => 'User not found.',
],
], 404);
}
return $this->createJsonResponse($user, 200);
}
/**
* @param array|JsonSerializable $body
* @param int $status
* @return ResponseInterface
*/
private function createJsonResponse($body, int $status): ResponseInterface
{
return $this->responseFactory
->createResponse($status)
->withBody($this->streamFactory->createStream(json_encode($body)))
->withHeader('content-type', 'application/json');
}
}