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

MigrationPlanCalculator::shouldExecuteMigration()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
cc 5
nc 5
nop 4
dl 0
loc 25
ccs 10
cts 11
cp 0.9091
crap 5.0187
rs 9.2088
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations;
6
7
use Doctrine\Migrations\Version\Direction;
8
use Doctrine\Migrations\Version\Version;
9
use function array_filter;
10
use function array_reverse;
11
use function count;
12
use function in_array;
13
14
/**
15
 * The MigrationPlanCalculator is responsible for calculating the plan for migrating from the current
16
 * version to another version.
17
 *
18
 * @internal
19
 */
20
final class MigrationPlanCalculator
21
{
22
    /** @var MigrationRepository */
23
    private $migrationRepository;
24
25 35
    public function __construct(MigrationRepository $migrationRepository)
26
    {
27 35
        $this->migrationRepository = $migrationRepository;
28 35
    }
29
30
    /** @return Version[] */
31 35
    public function getMigrationsToExecute(string $direction, string $to) : array
32
    {
33 35
        $allVersions = $this->migrationRepository->getMigrations();
34
35 35
        if ($direction === Direction::DOWN && count($allVersions) !== 0) {
36 8
            $allVersions = array_reverse($allVersions);
37
        }
38
39 35
        $migrated = $this->migrationRepository->getMigratedVersions();
40
41
        return array_filter($allVersions, function (Version $version) use (
42 33
            $migrated,
43 33
            $direction,
44 33
            $to
45
        ) {
46 33
            return $this->shouldExecuteMigration($direction, $version, $to, $migrated);
47 35
        });
48
    }
49
50
    /** @param string[] $migrated */
51 33
    private function shouldExecuteMigration(
52
        string $direction,
53
        Version $version,
54
        string $to,
55
        array $migrated
56
    ) : bool {
57 33
        $to = (int) $to;
58
59 33
        if ($direction === Direction::DOWN) {
60 8
            if (! in_array($version->getVersion(), $migrated, true)) {
61 5
                return false;
62
            }
63
64 6
            return (int) $version->getVersion() > $to;
65
        }
66
67 30
        if ($direction === Direction::UP) {
68 30
            if (in_array($version->getVersion(), $migrated, true)) {
69 9
                return false;
70
            }
71
72 29
            return (int) $version->getVersion() <= $to;
73
        }
74
75
        return false;
76
    }
77
}
78