Passed
Push — master ( 37f1a0...f026ca )
by Jakub
01:30
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\Filter;
10
use Zalas\Toolbox\Tool\Tool;
11
use Zalas\Toolbox\Tool\Tools;
12
13
final class JsonTools implements Tools
14
{
15
    /**
16
     * @var callable
17
     */
18
    private $resourceLocator;
19
20 12
    public function __construct(callable $resourceLocator)
21
    {
22 12
        $this->resourceLocator = $resourceLocator;
23
    }
24
25
    /**
26
     * @return Collection|Tool[]
27
     */
28 8
    public function all(Filter $filter): Collection
29
    {
30 8
        return $this->loadTools()->filter($filter);
31
    }
32
33 7
    private function loadTools(): Collection
34
    {
35
        return \array_reduce($this->resources(), function (Collection $tools, string $resource): Collection {
36 7
            return $tools->merge(Collection::create(
37 7
                \array_map(\sprintf('%s::import', ToolFactory::class), $this->loadJson($resource))
38
            ));
39 7
        }, Collection::create([]));
40
    }
41
42 7
    private function loadJson(string $resource): array
43
    {
44 7
        $json = \json_decode(\file_get_contents($resource), true);
45
46 7
        if (!$json) {
47 1
            throw new RuntimeException(\sprintf('Failed to parse json: "%s"', $resource));
48
        }
49
50 6
        if (!isset($json['tools']) || !\is_array($json['tools'])) {
51 2
            throw new RuntimeException(\sprintf('Failed to find any tools in: "%s".', $resource));
52
        }
53
54 4
        return $json['tools'];
55
    }
56
57 8
    private function resources(): array
58
    {
59 8
        $resources = \call_user_func($this->resourceLocator);
60
61
        return \array_map(function (string $resource) {
62 8
            if (!\is_readable($resource)) {
63 1
                throw new InvalidArgumentException(\sprintf('Could not read the file: "%s".', $resource));
64
            }
65
66 7
            return $resource;
67 8
        }, $resources);
68
    }
69
}
70