Passed
Pull Request — master (#120)
by Ralf
10:08
created

JsonHandler   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 31
rs 10
c 0
b 0
f 0
wmc 7
1
<?php
2
/**
3
 * Mime Type: application/json
4
 * @author Nathan Good <[email protected]>
5
 */
6
7
namespace Httpful\Handlers;
8
9
class JsonHandler extends MimeHandlerAdapter
10
{
11
    private $decode_as_array = false;
12
13
    public function init(array $args)
14
    {
15
        $this->decode_as_array = !!(array_key_exists('decode_as_array', $args) ? $args['decode_as_array'] : false);
16
    }
17
18
    /**
19
     * @param string $body
20
     * @return mixed
21
     */
22
    public function parse($body)
23
    {
24
        $body = $this->stripBom($body);
25
        if (empty($body))
26
            return null;
27
        $parsed = json_decode($body, $this->decode_as_array);
28
        if (is_null($parsed) && 'null' !== strtolower($body))
29
            throw new \Exception("Unable to parse response as JSON");
30
        return $parsed;
31
    }
32
33
    /**
34
     * @param mixed $payload
35
     * @return string
36
     */
37
    public function serialize($payload)
38
    {
39
        return json_encode($payload);
40
    }
41
}
42