Failed Conditions
Push — master ( 51f284...368556 )
by Jonathan
02:26
created

MigrationPlanCalculator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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