DataUtils   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 10
dl 0
loc 28
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A loadJson() 0 16 5
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