Passed
Pull Request — master (#638)
by Michael
02:49
created

MigrationDirectoryHelper::getMigrationDirectory()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 5
nop 0
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 4
rs 9.0534
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations\Tools\Console\Helper;
6
7
use Doctrine\Migrations\Configuration\Configuration;
8
use InvalidArgumentException;
9
use Symfony\Component\Console\Helper\Helper;
10
use const DIRECTORY_SEPARATOR;
11
use function date;
12
use function file_exists;
13
use function getcwd;
14
use function mkdir;
15
use function rtrim;
16
use function sprintf;
17
18
class MigrationDirectoryHelper extends Helper
19
{
20
    /** @var Configuration */
21
    private $configuration;
22
23 18
    public function __construct(Configuration $configuration)
24
    {
25 18
        $this->configuration = $configuration;
26 18
    }
27
28
    /** @throws InvalidArgumentException */
29 17
    public function getMigrationDirectory() : string
30
    {
31 17
        $dir = $this->configuration->getMigrationsDirectory();
32 17
        $dir = $dir ?? getcwd();
33 17
        $dir = rtrim($dir, '/');
34
35 17
        if (! file_exists($dir)) {
36 1
            throw new InvalidArgumentException(sprintf('Migrations directory "%s" does not exist.', $dir));
37
        }
38
39 16
        if ($this->configuration->areMigrationsOrganizedByYear()) {
40 3
            $dir .= $this->appendDir(date('Y'));
41
        }
42
43 16
        if ($this->configuration->areMigrationsOrganizedByYearAndMonth()) {
44 2
            $dir .= $this->appendDir(date('m'));
45
        }
46
47 16
        $this->createDirIfNotExists($dir);
48
49 16
        return $dir;
50
    }
51
52 3
    private function appendDir(string $dir) : string
53
    {
54 3
        return DIRECTORY_SEPARATOR . $dir;
55
    }
56
57 16
    private function createDirIfNotExists(string $dir) : void
58
    {
59 16
        if (file_exists($dir)) {
60 13
            return;
61
        }
62
63 3
        mkdir($dir, 0755, true);
64 3
    }
65
66
    public function getName() : string
67
    {
68
        return 'MigrationDirectory';
69
    }
70
}
71