Completed
Pull Request — master (#4)
by Jakub
03:36
created

ToolFactory::createCommands()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 13
nc 3
nop 2
dl 0
loc 20
ccs 12
cts 12
cp 1
crap 3
rs 9.8333
c 0
b 0
f 0
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