Passed
Push — master ( c9a7c7...1fb46e )
by Jakub
01:37
created

LazyRunner   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 47
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 3

6 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 3 1
A __construct() 0 5 1
guardServiceAvailability() 0 11 ?
A hp$0 ➔ guardServiceAvailability() 0 11 3
A initializeRunner() 0 7 2
A runner() 0 7 2
1
<?php declare(strict_types=1);
2
3
namespace Zalas\Toolbox\Cli\Runner;
4
5
use Psr\Container\ContainerExceptionInterface;
6
use Psr\Container\ContainerInterface;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Zalas\Toolbox\Runner\PassthruRunner;
9
use Zalas\Toolbox\Runner\Runner;
10
use Zalas\Toolbox\Tool\Command;
11
12
final class LazyRunner implements Runner
13
{
14
    private $container;
15
16
    private $runner;
17
18 12
    public function __construct(ContainerInterface $container)
19
    {
20 12
        $this->guardServiceAvailability($container);
21
22 12
        $this->container = $container;
23
    }
24
25 5
    public function run(Command $command): int
26
    {
27 5
        return $this->runner()->run($command);
28
    }
29
30 5
    private function runner(): Runner
31
    {
32 5
        if (null === $this->runner) {
33 5
            $this->runner = $this->initializeRunner();
34
        }
35
36 5
        return $this->runner;
37
    }
38
39 5
    private function initializeRunner(): Runner
40
    {
41 5
        if ($this->container->get(InputInterface::class)->getOption('dry-run')) {
42 3
            return $this->container->get(DryRunner::class);
43
        }
44
45 2
        return $this->container->get(PassthruRunner::class);
46
    }
47
48 12
    private function guardServiceAvailability(ContainerInterface $container): void
49
    {
50
        $requiredServices = [
51 12
            InputInterface::class,
52
            PassthruRunner::class,
53
            DryRunner::class,
54
        ];
55
56 12
        foreach ($requiredServices as $serviceId) {
57 12
            if (!$container->has($serviceId)) {
58
                throw new class(\sprintf('The service "%s" is missing.', $serviceId)) extends \LogicException implements ContainerExceptionInterface {
59
                };
60
            }
61
        }
62
    }
63
}
64