Passed
Pull Request — master (#739)
by Michael
02:38
created

MigrationDirectoryHelper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 92%

Importance

Changes 0
Metric Value
dl 0
loc 56
ccs 23
cts 25
cp 0.92
rs 10
c 0
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A appendDir() 0 3 1
A getName() 0 3 1
A getMigrationDirectory() 0 24 4
A createDirIfNotExists() 0 7 2
A __construct() 0 3 1
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 Doctrine\Migrations\Tools\Console\Exception\DirectoryDoesNotExist;
9
use const DIRECTORY_SEPARATOR;
10
use function assert;
11
use function date;
12
use function file_exists;
13
use function getcwd;
14
use function mkdir;
15
use function rtrim;
16
17
/**
18
 * The MigrationDirectoryHelper class is responsible for returning the directory that migrations are stored in.
19
 *
20
 * @internal
21
 */
22
class MigrationDirectoryHelper
23
{
24
    /** @var Configuration */
25
    private $configuration;
26
27 14
    public function __construct(Configuration $configuration)
28
    {
29 14
        $this->configuration = $configuration;
30 14
    }
31
32
    /**
33
     * @throws DirectoryDoesNotExist
34
     */
35 13
    public function getMigrationDirectory() : string
36
    {
37 13
        $dir = $this->configuration->getMigrationsDirectory();
38 13
        $dir = $dir ?? getcwd();
39
40 13
        assert($dir !== false, 'Unable to determine current working directory.');
41
42 13
        $dir = rtrim($dir, '/');
43
44 13
        if (! file_exists($dir)) {
45 1
            throw DirectoryDoesNotExist::new($dir);
46
        }
47
48 12
        if ($this->configuration->areMigrationsOrganizedByYear()) {
49 3
            $dir .= $this->appendDir(date('Y'));
50
        }
51
52 12
        if ($this->configuration->areMigrationsOrganizedByYearAndMonth()) {
53 2
            $dir .= $this->appendDir(date('m'));
54
        }
55
56 12
        $this->createDirIfNotExists($dir);
57
58 12
        return $dir;
59
    }
60
61 3
    private function appendDir(string $dir) : string
62
    {
63 3
        return DIRECTORY_SEPARATOR . $dir;
64
    }
65
66 12
    private function createDirIfNotExists(string $dir) : void
67
    {
68 12
        if (file_exists($dir)) {
69 9
            return;
70
        }
71
72 3
        mkdir($dir, 0755, true);
73 3
    }
74
75
    public function getName() : string
76
    {
77
        return 'MigrationDirectory';
78
    }
79
}
80