UpdateBundleVersionMigration   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 60
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A up() 0 17 3
B getLatestSuccessMigrationVersions() 0 18 6
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