JsonDecoder::decode()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 4
nop 1
1
<?php
2
namespace Michaels\Manager\Decoders;
3
4
use Michaels\Manager\Contracts\DecoderInterface;
5
use Michaels\Manager\Exceptions\JsonDecodingFailedException;
6
7
/**
8
 * A standard Json Decoder Module for the data manager file loader.
9
 *
10
 * @package Michaels\Manager
11
 */
12
class JsonDecoder implements DecoderInterface
13
{
14
    /** @var array Decoded data */
15
    protected $arrayData = [];
16
17
    /**
18
     * Decodes JSON data to array
19
     *
20
     * @param $data string
21
     * @return array
22
     * @throws JsonDecodingFailedException
23
     */
24
    public function decode($data)
25
    {
26
        if (is_string($data)) {
27
            $this->arrayData = json_decode($data, true); // true gives us associative arrays
28
        }
29
30
        if (!is_string($data) || !$this->isValidJson()) {
31
            throw new JsonDecodingFailedException('The data provided was not proper JSON');
32
        }
33
34
        return $this->arrayData;
35
    }
36
37
    /**
38
     * Returns MimeType
39
     * @return string[]
40
     */
41
    public function getMimeType()
42
    {
43
        return ['json'];
44
    }
45
46
    /**
47
     * Checks if the input is really a json string and if the PHP Json decoding was successful.
48
     * @return boolean
49
     */
50
    protected function isValidJson()
51
    {
52
        return (json_last_error() === JSON_ERROR_NONE);
53
    }
54
}
55