Completed
Push — master ( e93a4a...079c5b )
by Théo
02:06
created

BaseCommand::changeWorkingDirectory()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 4
nop 1
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
ccs 0
cts 15
cp 0
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the humbug/php-scoper package.
7
 *
8
 * Copyright (c) 2017 Théo FIDRY <[email protected]>,
9
 *                    Pádraic Brady <[email protected]>
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace Humbug\PhpScoper\Console\Command;
16
17
use InvalidArgumentException;
18
use Symfony\Component\Console\Command\Command;
19
use Symfony\Component\Console\Exception\RuntimeException;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Input\InputOption;
22
23
abstract class BaseCommand extends Command
24
{
25
    private const WORKING_DIR_OPT = 'working-dir';
26
27
    /**
28
     * @inheritdoc
29
     */
30
    protected function configure(): void
31
    {
32
        $this->addOption(
33
            self::WORKING_DIR_OPT,
34
            'd',
35
            InputOption::VALUE_REQUIRED,
36
            'If specified, use the given directory as working directory.',
37
            null
38
        );
39
    }
40
41
    final public function changeWorkingDirectory(InputInterface $input): void
42
    {
43
        $workingDir = $input->getOption(self::WORKING_DIR_OPT);
44
45
        if (null === $workingDir) {
46
            return;
47
        }
48
49
        if (false === file_exists($workingDir)) {
50
            throw new InvalidArgumentException(
51
                sprintf(
52
                    'Could not change the working directory to "%s": directory does not exists.',
53
                    $workingDir
54
                )
55
            );
56
        }
57
58
        if (false === chdir($workingDir)) {
59
            throw new RuntimeException(
60
                sprintf(
61
                    'Failed to change the working directory to "%s" from "%s".',
62
                    $workingDir,
63
                    getcwd()
64
                )
65
            );
66
        }
67
    }
68
}
69