1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Zalas\Toolbox\Json\Factory; |
4
|
|
|
|
5
|
|
|
use Zalas\Toolbox\Tool\Collection; |
6
|
|
|
use Zalas\Toolbox\Tool\Command; |
7
|
|
|
use Zalas\Toolbox\Tool\Command\MultiStepCommand; |
8
|
|
|
use Zalas\Toolbox\Tool\Command\TestCommand; |
9
|
|
|
use Zalas\Toolbox\Tool\Tool; |
10
|
|
|
|
11
|
|
|
final class ToolFactory |
12
|
|
|
{ |
13
|
17 |
|
public static function import(array $tool): Tool |
14
|
|
|
{ |
15
|
17 |
|
Assert::requireFields(['name', 'summary', 'website', 'command', 'test'], $tool, 'tool'); |
16
|
|
|
|
17
|
12 |
|
return new Tool($tool['name'], $tool['summary'], $tool['website'], self::importCommand($tool), new TestCommand($tool['test'], $tool['name'])); |
18
|
|
|
} |
19
|
|
|
|
20
|
12 |
|
private static function importCommand(array $tool): Command |
21
|
|
|
{ |
22
|
12 |
|
$commands = Collection::create([]); |
23
|
|
|
|
24
|
12 |
|
foreach ($tool['command'] as $type => $command) { |
25
|
11 |
|
$commands = $commands->merge(self::createCommands($type, $command)); |
26
|
|
|
} |
27
|
|
|
|
28
|
11 |
|
if (0 === $commands->count()) { |
29
|
1 |
|
throw new \RuntimeException(\sprintf('No valid command defined for the tool: %s', \json_encode($tool))); |
30
|
|
|
} |
31
|
|
|
|
32
|
10 |
|
return 1 === $commands->count() ? $commands->toArray()[0] : new MultiStepCommand($commands); |
33
|
|
|
} |
34
|
|
|
|
35
|
11 |
|
private static function createCommands($type, $command): Collection |
36
|
|
|
{ |
37
|
|
|
$factories = [ |
38
|
11 |
|
'phar-download' => \sprintf('%s::import', PharDownloadCommandFactory::class), |
39
|
11 |
|
'file-download' => \sprintf('%s::import', FileDownloadCommandFactory::class), |
40
|
11 |
|
'box-build' => \sprintf('%s::import', BoxBuildCommandFactory::class), |
41
|
11 |
|
'composer-install' => \sprintf('%s::import', ComposerInstallCommandFactory::class), |
42
|
11 |
|
'composer-global-install' => \sprintf('%s::import', ComposerGlobalInstallCommandFactory::class), |
43
|
11 |
|
'composer-bin-plugin' => \sprintf('%s::import', ComposerBinPluginCommandFactory::class), |
44
|
|
|
]; |
45
|
|
|
|
46
|
11 |
|
if (!isset($factories[$type])) { |
47
|
1 |
|
throw new \RuntimeException(\sprintf('Unrecognised command: "%s". Supported commands are: "%s".', $type, \implode(', ', \array_keys($factories)))); |
48
|
|
|
} |
49
|
|
|
|
50
|
10 |
|
$command = !\is_numeric(\key($command)) ? [$command] : $command; |
51
|
|
|
|
52
|
|
|
return Collection::create(\array_map(function ($c) use ($type, $factories) { |
53
|
10 |
|
return $factories[$type]($c); |
54
|
10 |
|
}, $command)); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|