getLatestSuccessMigrationVersions()   B
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 18
rs 8.8571
cc 6
eloc 11
nc 5
nop 0
1
<?php
2
3
namespace RDV\Bundle\MigrationBundle\Migration;
4
5
use Doctrine\DBAL\Schema\Schema;
6
7
class UpdateBundleVersionMigration implements Migration, FailIndependentMigration
8
{
9
    /** @var MigrationState[] */
10
    protected $migrations;
11
12
    /**
13
     * @param MigrationState[] $migrations
14
     */
15
    public function __construct(array $migrations)
16
    {
17
        $this->migrations = $migrations;
18
    }
19
20
    /**
21
     * @inheritdoc
22
     */
23
    public function up(Schema $schema, QueryBag $queries)
24
    {
25
        $bundleVersions = $this->getLatestSuccessMigrationVersions();
26
        if (!empty($bundleVersions)) {
27
            $date = new \DateTime();
28
            foreach ($bundleVersions as $bundleName => $bundleVersion) {
29
                $sql = sprintf(
30
                    "INSERT INTO %s (bundle, version, loaded_at) VALUES ('%s', '%s', '%s')",
31
                    Tables::MIGRATION_TABLE,
32
                    $bundleName,
33
                    $bundleVersion,
34
                    $date->format('Y-m-d H:i:s')
35
                );
36
                $queries->addQuery($sql);
37
            }
38
        }
39
    }
40
41
    /**
42
     * Extracts latest version of successfully finished migrations for each bundle
43
     *
44
     * @return string[]
45
     *      key   = bundle name
46
     *      value = version
47
     */
48
    protected function getLatestSuccessMigrationVersions()
49
    {
50
        $result = [];
51
        foreach ($this->migrations as $migration) {
52
            if (!$migration->isSuccessful() || !$migration->getVersion()) {
53
                continue;
54
            }
55
            if (isset($result[$migration->getBundleName()])) {
56
                if (version_compare($result[$migration->getBundleName()], $migration->getVersion()) === -1) {
57
                    $result[$migration->getBundleName()] = $migration->getVersion();
58
                }
59
            } else {
60
                $result[$migration->getBundleName()] = $migration->getVersion();
61
            }
62
        }
63
64
        return $result;
65
    }
66
}
67