RunnerFactory.php$0 ➔ targetDir()   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 3
rs 9.7998
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace Zalas\Toolbox\Cli\ServiceContainer;
4
5
use Psr\Container\ContainerExceptionInterface;
6
use Psr\Container\ContainerInterface;
7
use Psr\Container\NotFoundExceptionInterface;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Output\OutputInterface;
10
use Zalas\Toolbox\Cli\Runner\DryRunner;
11
use Zalas\Toolbox\Runner\ParametrisedRunner;
12
use Zalas\Toolbox\Runner\PassthruRunner;
13
use Zalas\Toolbox\Runner\Runner;
14
15
class RunnerFactory
16
{
17
    private ContainerInterface $container;
18
19 10
    public function __construct(ContainerInterface $container)
20
    {
21 10
        $this->container = $container;
22
    }
23
24
    /**
25
     * @throws ContainerExceptionInterface
26
     * @throws NotFoundExceptionInterface
27
     */
28 7
    public function createRunner(): Runner
29
    {
30 7
        $runner = $this->createRealRunner();
31
32 7
        if ($parameters = $this->parameters()) {
33 4
            return new ParametrisedRunner($runner, $parameters);
34
        }
35
36 2
        return $runner;
37
    }
38
39
    /**
40
     * @throws ContainerExceptionInterface
41
     * @throws NotFoundExceptionInterface
42
     */
43 7
    private function createRealRunner(): DryRunner|PassthruRunner
44
    {
45 7
        if ($this->container->get(InputInterface::class)->getOption('dry-run')) {
46 4
            return new DryRunner($this->container->get(OutputInterface::class));
47
        }
48
49 3
        return new PassthruRunner();
50
    }
51
52
    /**
53
     * @throws ContainerExceptionInterface
54
     * @throws NotFoundExceptionInterface
55
     */
56 7
    private function parameters(): array
57
    {
58 7
        if ($targetDir = $this->targetDir()) {
59 4
            return ['%target-dir%' => $targetDir];
60
        }
61
62 2
        return [];
63
    }
64
65
    /**
66
     * @throws ContainerExceptionInterface
67
     * @throws NotFoundExceptionInterface
68
     */
69 7
    private function targetDir(): ?string
70
    {
71 7
        if (!$this->container->get(InputInterface::class)->hasOption('target-dir')) {
72 2
            return null;
73
        }
74
75 5
        $targetDir = $this->container->get(InputInterface::class)->getOption('target-dir');
76
77 5
        if (!\is_dir($targetDir)) {
78 1
            throw new class(\sprintf('The target dir does not exist: "%s".', $targetDir)) extends \RuntimeException implements ContainerExceptionInterface {
79 1
            };
80
        }
81
82 4
        return \realpath($targetDir);
83
    }
84
}
85