Completed
Pull Request — master (#2)
by Joao
03:57
created

AbstractDatabase::getVersion()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 17
rs 9.4285
cc 3
eloc 11
nc 3
nop 0
1
<?php
2
3
namespace ByJG\DbMigration\Database;
4
5
use ByJG\AnyDataset\DbDriverInterface;
6
use ByJG\DbMigration\Exception\DatabaseNotVersionedException;
7
use ByJG\DbMigration\Exception\OldVersionSchemaException;
8
9
abstract class AbstractDatabase implements DatabaseInterface
10
{
11
    /**
12
     * @var DbDriverInterface
13
     */
14
    private $dbDriver;
15
16
    /**
17
     * Command constructor.
18
     *
19
     * @param DbDriverInterface $dbDriver
20
     */
21
    public function __construct(DbDriverInterface $dbDriver)
22
    {
23
        $this->dbDriver = $dbDriver;
24
    }
25
26
    /**
27
     * @return DbDriverInterface
28
     */
29
    public function getDbDriver()
30
    {
31
        return $this->dbDriver;
32
    }
33
34
    public function getVersion()
35
    {
36
        $result = [];
37
        try {
38
            $result['version'] = $this->getDbDriver()->getScalar('SELECT version FROM migration_version');
39
        } catch (\Exception $ex) {
40
            throw new DatabaseNotVersionedException('This database does not have a migration version. Please use "migrate reset" or "migrate install" to create one.');
41
        }
42
43
        try {
44
            $result['status'] = $this->getDbDriver()->getScalar('SELECT status FROM migration_version');
45
        } catch (\Exception $ex) {
46
            throw new OldVersionSchemaException('This database does not have a migration version. Please use "migrate install" for update it.');
47
        }
48
49
        return $result;
50
    }
51
52
    public function setVersion($version, $status)
53
    {
54
        $this->getDbDriver()->execute(
55
            'UPDATE migration_version SET version = :version, status = :status',
56
            [
57
                'version' => $version,
58
                'status' => $status
59
            ]
60
        );
61
    }
62
63
    protected function checkExistsVersion()
64
    {
65
        // Get the version to check if exists
66
        $versionInfo = $this->getVersion();
67
        if (empty($versionInfo['version'])) {
68
            $this->getDbDriver()->execute("insert into migration_version values(0, 'unknow')");
69
        }
70
    }
71
72
    public function updateVersionTable()
73
    {
74
        $currentVersion = $this->getDbDriver()->getScalar('select version from migration_version');
75
        $this->getDbDriver()->execute('drop table migration_version');
76
        $this->createVersion();
77
        $this->setVersion($currentVersion, 'unknow');
78
   }
79
}
80