Completed
Pull Request — master (#5)
by Randy
02:04
created

JSend::respondWith()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
3
namespace Demv\JSend;
4
5
use Seld\JsonLint\JsonParser;
6
use Seld\JsonLint\ParsingException;
7
use function Dgame\Ensurance\ensure;
8
9
/**
10
 * Class JSend
11
 * @package Demv\JSend
12
 */
13
final class JSend
14
{
15
    /**
16
     * @param array $response
17
     *
18
     * @return JSendResponseInterface
19
     */
20
    public static function interpret(array $response): JSendResponseInterface
21
    {
22
        ensure($response)->isArray()->hasKey('status')->orThrow('Key "status" is required');
23
24
        $status = Status::instance($response['status']);
25
        if ($status->isSuccess() || $status->isFail()) {
26
            ensure($response)->isArray()->hasKey('data')->orThrow('Key "data" is required');
27
28
            return new JSendResponse($status, $response['data']);
29
        }
30
31
        return new JSendErrorResponse($status, $response);
32
    }
33
34
    /**
35
     * @param string $json
36
     *
37
     * @return JSendResponseInterface
38
     * @throws ParsingException
39
     */
40
    public static function decode(string $json): JSendResponseInterface
41
    {
42
        $parser = new JsonParser();
43
        $result = $parser->parse($json, JsonParser::PARSE_TO_ASSOC | JsonParser::DETECT_KEY_CONFLICTS);
44
45
        return self::interpret($result);
46
    }
47
48
    /**
49
     * @param array $response
50
     * @param int   $options
51
     *
52
     * @return string
53
     */
54
    public static function encode(array $response, int $options = 0): string
55
    {
56
        ensure($response)->isNotEmpty()->orThrow('Empty response cannot be converted to valid JSend-JSON');
57
        ensure($response)->isArray()->hasKey('status')->orThrow('Key "status" is required');
58
        $status = Status::instance($response['status']);
59
        if ($status->isError()) {
60
            ensure($response)->isArray()->hasKey('message')->orThrow('Need a descriptive error-message');
61
        }
62
63
        return json_encode($response, $options);
64
    }
65
66
    /**
67
     * @param JSendResponseInterface $response
68
     *
69
     * @return int
70
     */
71
    public static function getDefaultHttpStatusCode(JSendResponseInterface $response): int
72
    {
73
        if ($response->getStatus()->isError()) {
74
            return $response->getError()->getCode() ?? 500;
75
        }
76
77
        return 200;
78
    }
79
}
80