Passed
Push — master ( fbe91f...55cf70 )
by Adrian Florin
02:52
created

JsonContent::decodeJson()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * This file is part of the NeedleProject\FileIo package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace NeedleProject\FileIo\Content;
9
10
use NeedleProject\FileIo\Exception\ContentException;
11
12
/**
13
 * Class JsonContent
14
 *
15
 * @package NeedleProject\FileIo\Content
16
 * @author Adrian Tilita <[email protected]>
17
 * @copyright 2017 Adrian Tilita
18
 * @license https://opensource.org/licenses/MIT MIT Licence
19
 */
20
class JsonContent extends Content implements ContentInterface
21
{
22
    /**
23
     * Return the content as an array
24
     *
25
     * @return array
26
     * @throws \NeedleProject\FileIo\Exception\ContentException
27
     */
28 3
    public function getArray(): array
29
    {
30 3
        return $this->decodeJson(true);
31
    }
32
33
    /**
34
     * @return \stdClass
35
     * @throws \NeedleProject\FileIo\Exception\ContentException
36
     */
37 3
    public function getObject()
38
    {
39 3
        return $this->decodeJson();
40
    }
41
42
    /**
43
     * @param bool $asArray
44
     * @return mixed
45
     * @throws \NeedleProject\FileIo\Exception\ContentException
46
     */
47 5
    private function decodeJson(bool $asArray = false)
48
    {
49 5
        $content = json_decode($this->get(), $asArray);
50 5
        if (json_last_error() !== JSON_ERROR_NONE) {
51 4
            throw new ContentException(
52 4
                sprintf("Could not decode content, got %s", json_last_error_msg())
53
            );
54
        }
55 1
        return $content;
56
    }
57
}
58