FileUtility::jsonFileToArray()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.4222
c 0
b 0
f 0
cc 5
nc 4
nop 1
crap 5
1
<?php
2
3
namespace Botonomous\utility;
4
5
use Botonomous\BotonomousException;
6
7
/**
8
 * Class FileUtility.
9
 */
10
class FileUtility extends AbstractUtility
11
{
12
    const EMPTY_FILE_PATH_MESSAGE = 'File path is empty';
13
    const MISSING_FILE_MESSAGE = 'File does not exist or is not a file';
14
    const INVALID_JSON_FILE_MESSAGE = 'File is not a json file';
15
16
    /**
17
     * Validate and convert a (JSON) file content to a PHP array.
18
     *
19
     * @param $filePath
20
     *
21
     * @throws \Exception
22
     *
23
     * @return array|mixed
24
     */
25 24
    public function jsonFileToArray(string $filePath)
26
    {
27 24
        if (empty($filePath)) {
28 1
            throw new BotonomousException(self::EMPTY_FILE_PATH_MESSAGE);
29
        }
30
31 23
        if (!file_exists($filePath) || !is_file($filePath)) {
32 1
            throw new BotonomousException(self::MISSING_FILE_MESSAGE);
33
        }
34
35 22
        if (pathinfo($filePath, PATHINFO_EXTENSION) !== 'json') {
36 1
            throw new BotonomousException(self::INVALID_JSON_FILE_MESSAGE);
37
        }
38
39 21
        return (new StringUtility())->jsonToArray(file_get_contents($filePath));
40
    }
41
}
42