Passed
Push — master ( a4f7f2...d3cc39 )
by Melech
04:09
created

SqlFileMigration   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 11
c 0
b 0
f 0
dl 0
loc 70
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A runFailure() 0 2 1
A rollbackMigration() 0 3 1
A runMigration() 0 3 1
A executeSql() 0 17 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Valkyrja Framework package.
7
 *
8
 * (c) Melech Mizrachi <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Valkyrja\Orm\Schema;
15
16
use Throwable;
17
use Valkyrja\Exception\RuntimeException;
18
19
use function explode;
20
use function file_get_contents;
21
use function trim;
22
23
/**
24
 * Class SqlFileMigration.
25
 */
26
abstract class SqlFileMigration extends TransactionalMigration
27
{
28
    /**
29
     * @inheritDoc
30
     */
31
    protected function runMigration(): void
32
    {
33
        $this->executeSql($this->getRunMigrationFilePath());
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    protected function rollbackMigration(): void
40
    {
41
        $this->executeSql($this->getRollbackMigrationFilePath());
42
    }
43
44
    /**
45
     * Execute sql.
46
     *
47
     * @param string $filePath The sql file path
48
     *
49
     * @return void
50
     */
51
    protected function executeSql(string $filePath): void
52
    {
53
        $sql = file_get_contents($filePath);
54
55
        if ($sql === false) {
56
            throw new RuntimeException("Invalid file $filePath given");
57
        }
58
59
        foreach (explode(';', trim($sql)) as $queryString) {
60
            if (! $queryString) {
61
                continue;
62
            }
63
64
            $statement = $this->orm->prepare($queryString);
65
66
            if (! $statement->execute()) {
67
                throw new RuntimeException($statement->errorMessage() ?? 'Error occurred');
68
            }
69
        }
70
    }
71
72
    /**
73
     * Do on run failure.
74
     *
75
     * @param Throwable $exception The exception
76
     *
77
     * @return void
78
     */
79
    protected function runFailure(Throwable $exception): void
80
    {
81
    }
82
83
    /**
84
     * Get the run sql file path.
85
     *
86
     * @return string
87
     */
88
    abstract protected function getRunMigrationFilePath(): string;
89
90
    /**
91
     * Get the rollback sql file path.
92
     *
93
     * @return string
94
     */
95
    abstract protected function getRollbackMigrationFilePath(): string;
96
}
97