Passed
Branch master (3ca6b5)
by n
02:12
created

UserShowJsonResponder   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 3
dl 0
loc 49
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A respond() 0 13 2
A createJsonResponse() 0 7 1
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