DataUtils::loadJson()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 16
rs 9.6111
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebThumbnailer\Utils;
6
7
use WebThumbnailer\Exception\BadRulesException;
8
use WebThumbnailer\Exception\IOException;
9
10
/**
11
 * Util class for operation regarding data.
12
 */
13
class DataUtils
14
{
15
    /**
16
     * Read a JSON file, and convert it to an array.
17
     *
18
     * @param string $jsonFile JSON file.
19
     *
20
     * @return mixed[] JSON loaded in an array.
21
     *
22
     * @throws IOException       JSON file is not readable
23
     * @throws BadRulesException JSON file badly formatted.
24
     */
25
    public static function loadJson(string $jsonFile): array
26
    {
27
        if (!file_exists($jsonFile) || !is_readable($jsonFile)) {
28
            throw new IOException('JSON resource file not found or not readable.');
29
        }
30
31
        $data = json_decode(file_get_contents($jsonFile) ?: '', true);
32
        if ($data === null) {
33
            $error = json_last_error();
34
            $msg = json_last_error_msg();
35
            throw new BadRulesException(
36
                'An error occured while parsing JSON file: error code #' . $error . ': ' . $msg
37
            );
38
        }
39
40
        return $data;
41
    }
42
}
43