ResponseFactory   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 7
dl 0
loc 78
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A instance() 0 8 2
A convert() 0 10 1
A success() 0 4 1
A fail() 0 4 1
A error() 0 8 3
1
<?php
2
3
namespace Demv\JSend;
4
5
use Psr\Http\Message\ResponseInterface;
6
use Seld\JsonLint\JsonParser;
7
8
/**
9
 * Class ResponseFactory
10
 * @package Demv\JSend
11
 */
12
final class ResponseFactory
13
{
14
    /**
15
     * @var ResponseFactory
16
     */
17
    private static $instance;
18
19
    /**
20
     * ResponseFactory constructor.
21
     */
22
    private function __construct()
23
    {
24
    }
25
26
    /**
27
     * @return ResponseFactory
28
     */
29
    public static function instance(): self
30
    {
31
        if (self::$instance === null) {
32
            self::$instance = new self();
33
        }
34
35
        return self::$instance;
36
    }
37
38
    /**
39
     * @param ResponseInterface $response
40
     *
41
     * @return JSendResponseInterface
42
     * @throws \Seld\JsonLint\ParsingException
43
     */
44
    public function convert(ResponseInterface $response): JSendResponseInterface
45
    {
46
        $content = $response->getBody()->getContents();
47
48
        $parser         = new JsonParser();
49
        $result         = $parser->parse($content, JsonParser::PARSE_TO_ASSOC | JsonParser::DETECT_KEY_CONFLICTS);
50
        $result['code'] = $response->getStatusCode();
51
52
        return JSend::interpret($result);
53
    }
54
55
    /**
56
     * @param array|null $data
57
     *
58
     * @return JSendResponseInterface
59
     */
60
    public function success(array $data = null): JSendResponseInterface
61
    {
62
        return new JSendResponse(Status::success(), $data);
63
    }
64
65
    /**
66
     * @param array|null $data
67
     *
68
     * @return JSendResponseInterface
69
     */
70
    public function fail(array $data = null): JSendResponseInterface
71
    {
72
        return new JSendResponse(Status::fail(), $data);
73
    }
74
75
    /**
76
     * @param array    $response
77
     * @param int|null $code
78
     *
79
     * @return JSendResponseInterface
80
     */
81
    public function error(array $response, int $code = null): JSendResponseInterface
82
    {
83
        if ($code !== null || !array_key_exists('code', $response)) {
84
            $response['code'] = $code;
85
        }
86
87
        return new JSendErrorResponse(Status::error(), $response);
88
    }
89
}
90