|
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\Tools; |
|
11
|
|
|
|
|
12
|
|
|
final class JsonTools implements Tools |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var callable |
|
16
|
|
|
*/ |
|
17
|
|
|
private $resourceLocator; |
|
18
|
|
|
|
|
19
|
12 |
|
public function __construct(callable $resourceLocator) |
|
20
|
|
|
{ |
|
21
|
12 |
|
$this->resourceLocator = $resourceLocator; |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param Filter $filter |
|
26
|
|
|
* @return Collection |
|
27
|
|
|
*/ |
|
28
|
8 |
|
public function all(Filter $filter): Collection |
|
29
|
|
|
{ |
|
30
|
8 |
|
return $this->loadTools()->filter($filter); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
8 |
|
private function loadTools(): Collection |
|
34
|
|
|
{ |
|
35
|
8 |
|
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
|
7 |
|
)); |
|
39
|
8 |
|
}, 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
|
8 |
|
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
|
|
|
|