Passed
Push — master ( d8a9f3...906de1 )
by Théo
02:24
created

src/Console/Command/ChangeableWorkingDirectory.php (1 issue)

Labels
Severity
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the box project.
7
 *
8
 * (c) Kevin Herrera <[email protected]>
9
 *     Théo Fidry <[email protected]>
10
 *
11
 * This source file is subject to the MIT license that is bundled
12
 * with this source code in the file LICENSE.
13
 */
14
15
namespace KevinGH\Box\Console\Command;
16
17
use Assert\Assertion;
18
use function chdir;
19
use function getcwd;
20
use function sprintf;
21
use Symfony\Component\Console\Exception\RuntimeException;
22
use Symfony\Component\Console\Input\InputInterface;
23
use Symfony\Component\Console\Input\InputOption;
24
25
/**
26
 * @private
27
 */
28
trait ChangeableWorkingDirectory
29
{
30
    /** @internal using a static property as traits cannot have constants */
31
    private static $WORKING_DIR_OPT = 'working-dir';
32
33
    final public function changeWorkingDirectory(InputInterface $input): void
34
    {
35
        $workingDir = $input->getOption(self::$WORKING_DIR_OPT);
36
37
        if (null === $workingDir) {
38
            return;
39
        }
40
41
        Assertion::directory(
42
            $workingDir,
0 ignored issues
show
It seems like $workingDir can also be of type string[]; however, parameter $value of Assert\Assertion::directory() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

42
            /** @scrutinizer ignore-type */ $workingDir,
Loading history...
43
            'Could not change the working directory to "%s": directory does not exists or file is not a directory.'
44
        );
45
46
        if (false === chdir($workingDir)) {
47
            throw new RuntimeException(
48
                sprintf(
49
                    'Failed to change the working directory to "%s" from "%s".',
50
                    $workingDir,
51
                    getcwd()
52
                )
53
            );
54
        }
55
    }
56
57
    private function configureWorkingDirOption(): void
58
    {
59
        $this->addOption(
60
            self::$WORKING_DIR_OPT,
61
            'd',
62
            InputOption::VALUE_REQUIRED,
63
            'If specified, use the given directory as working directory.',
64
            null
65
        );
66
    }
67
}
68