Passed
Push — master ( 254d09...309d02 )
by Jakub
01:36
created

JsonTools::loadJson()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 6
nc 3
nop 1
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 4
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Zalas\Toolbox\Json;
4
5
use InvalidArgumentException;
6
use RuntimeException;
7
use Zalas\Toolbox\Json\Factory\ToolFactory;
8
use Zalas\Toolbox\Tool\Collection;
9
use Zalas\Toolbox\Tool\Tool;
10
use Zalas\Toolbox\Tool\Tools;
11
12
final class JsonTools implements Tools
13
{
14
    /**
15
     * @var callable
16
     */
17
    private $resourceLocator;
18
19 10
    public function __construct(callable $resourceLocator)
20
    {
21 10
        $this->resourceLocator = $resourceLocator;
22
    }
23
24
    /**
25
     * @return Collection|Tool[]
26
     */
27 5
    public function all(): Collection
28
    {
29
        return \array_reduce($this->resources(), function (Collection $tools, string $resource): Collection {
30 5
            return $tools->merge(Collection::create(
31 5
                \array_map(\sprintf('%s::import', ToolFactory::class), $this->loadJson($resource))
32
            ));
33 5
        }, Collection::create([]));
34
    }
35
36 5
    private function loadJson(string $resource): array
37
    {
38 5
        $json = \json_decode(\file_get_contents($resource), true);
39
40 5
        if (!$json) {
41 1
            throw new RuntimeException(\sprintf('Failed to parse json: "%s"', $resource));
42
        }
43
44 4
        if (!isset($json['tools']) || !\is_array($json['tools'])) {
45 2
            throw new RuntimeException(\sprintf('Failed to find any tools in: "%s".', $resource));
46
        }
47
48 2
        return $json['tools'];
49
    }
50
51 6
    private function resources(): array
52
    {
53 6
        $resources = \call_user_func($this->resourceLocator);
54
55
        return \array_map(function (string $resource) {
56 6
            if (!\is_readable($resource)) {
57 1
                throw new InvalidArgumentException(\sprintf('Could not read the file: "%s".', $resource));
58
            }
59
60 5
            return $resource;
61 6
        }, $resources);
62
    }
63
}
64