JsonResponseContext::__toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace GinoPane\NanoRest\Response;
4
5
use GinoPane\NanoRest\Exceptions\ResponseContextException;
6
7
/**
8
 * Class JsonResponseContext
9
 *
10
 * Response context with JSON handling
11
 */
12
class JsonResponseContext extends ResponseContextAbstract
13
{
14
    /**
15
     * Get raw result data
16
     *
17
     * @param array $options
18
     *
19
     * @return string|null
20
     */
21
    public function getRaw(array $options = array()): ?string
22
    {
23
        return $this->getContent();
24
    }
25
26
    /**
27
     * Get result data as array
28
     *
29
     * @param array $options
30
     *
31
     * @return array
32
     */
33
    public function getArray(array $options = array()): array
34
    {
35
        $content = $this->getContent();
36
37
        if (is_null($content)) {
38
            return (array)$content;
39
        }
40
41
        return json_decode($this->content, true);
42
    }
43
44
    /**
45
     * Get result data as object
46
     *
47
     * @param array $options
48
     *
49
     * @return mixed
50
     */
51
    public function getObject(array $options = array())
52
    {
53
        $content = $this->getContent();
54
55
        if (is_null($content)) {
56
            return (object)$content;
57
        }
58
59
        return json_decode($this->content, false);
60
    }
61
62
    /**
63
     * String representation of response for debug purposes
64
     *
65
     * @return string
66
     */
67
    public function __toString(): string
68
    {
69
        return json_encode(json_decode($this->content), JSON_PRETTY_PRINT);
70
    }
71
72
    /**
73
     * Makes sure that $content is valid for this AbstractResponseContext instance
74
     *
75
     * @param string $content
76
     *
77
     * @throws ResponseContextException
78
     *
79
     * @return bool
80
     */
81
    protected function assertIsValid(string $content): bool
82
    {
83
        json_decode($content);
84
85
        if (json_last_error() !== JSON_ERROR_NONE) {
86
            $error = json_last_error_msg();
87
88
            throw new ResponseContextException($error);
89
        }
90
91
        return true;
92
    }
93
}
94