OptimisedComposerBinPluginCommand::commandsToRun()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Zalas\Toolbox\Tool\Command;
4
5
use InvalidArgumentException;
6
use Zalas\Toolbox\Tool\Collection;
7
use Zalas\Toolbox\Tool\Command;
8
9
final class OptimisedComposerBinPluginCommand implements Command
10
{
11
    private Collection $commands;
12
13 7
    public function __construct(Collection $commands)
14
    {
15 7
        if ($commands->empty()) {
16 1
            throw new InvalidArgumentException('Collection of composer bin plugin commands cannot be empty.');
17
        }
18
19 6
        $this->commands = $commands->filter(function (ComposerBinPluginCommand $command) {
20 6
            return $command;
21 6
        });
22
    }
23
24 5
    public function __toString(): string
25
    {
26 5
        return \implode(' && ', \array_merge($this->commandsToRun($this->packagesGroupedByNamespace()), $this->linksToCreate()));
27
    }
28
29 5
    private function packagesGroupedByNamespace(): array
30
    {
31 5
        return $this->commands->reduce([], function (array $packages, ComposerBinPluginCommand $command) {
32 5
            $packages[$command->namespace()][] = $command->package();
33
34 5
            return $packages;
35 5
        });
36
    }
37
38 5
    private function commandToRun(string $namespace, array $packages): string
39
    {
40 5
        return \sprintf('composer global bin %s require --prefer-dist --update-no-dev -n %s', $namespace, \implode(' ', $packages));
41
    }
42
43 5
    private function commandsToRun(array $packagesGrouped): array
44
    {
45 5
        return \array_map([$this, 'commandToRun'], \array_keys($packagesGrouped), $packagesGrouped);
46
    }
47
48 5
    private function linksToCreate(): array
49
    {
50 5
        return $this->commands
51 5
            ->filter(function (ComposerBinPluginCommand $command) {
52 5
                return !$command->links()->empty();
53 5
            })
54 5
            ->map(function (ComposerBinPluginCommand $command) {
55 1
                return $command->links()->reduce('', function (string $command, ComposerBinPluginLinkCommand $link) {
56 1
                    return !empty($command) ? $command.' && '.$link : $link;
57 1
                });
58 5
            })
59 5
            ->toArray();
60
    }
61
}
62