JsonReader   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 32
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A read() 0 21 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ReliqArts\DirectTranslator\Vocabulary\Reader;
6
7
use DomainException;
8
use Exception;
9
use ReliqArts\DirectTranslator\Vocabulary\Exception\ReadingFailed;
10
use ReliqArts\DirectTranslator\Vocabulary\Reader;
11
12
final class JsonReader implements Reader
13
{
14
    private const KEY_URL = 'url';
15
16
    /**
17
     * @param string $path
18
     *
19
     * @throws ReadingFailed
20
     *
21
     * @return array
22
     */
23
    public function read(string $path): array
24
    {
25
        try {
26
            $filePath = $path;
27
28
            do {
29
                $json = file_get_contents($filePath);
30
                $content = json_decode($json, true);
31
                $filePath = $content[self::KEY_URL] ?? null;
32
            } while (!empty($filePath));
33
34
            if (empty($content)) {
35
                throw new DomainException(sprintf('No/invalid content found.'));
36
            }
37
38
            return $content;
39
        } catch (Exception $exception) {
40
            throw new ReadingFailed(
41
                sprintf('Failed to read vocabulary at: `%s`', $path),
42
                $exception->getCode(),
43
                $exception
44
            );
45
        }
46
    }
47
}
48