Completed
Branch feature/pre-split (67216b)
by Anton
03:28
created

MigrationCapsule::getDatabase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
namespace Spiral\Migrations;
9
10
use Spiral\Database\DatabaseManager;
11
use Spiral\Database\Entities\Database;
12
use Spiral\Database\Entities\Table;
13
use Spiral\Database\Schemas\Prototypes\AbstractTable;
14
use Spiral\Migrations\Exceptions\CapsuleException;
15
16
/**
17
 * Isolates set of table specific operations and schemas into one place. Kinda repository.
18
 */
19
class MigrationCapsule implements CapsuleInterface
20
{
21
    /**
22
     * Cached set of table schemas.
23
     *
24
     * @var array
25
     */
26
    private $schemas = [];
27
28
    /**
29
     * @invisible
30
     * @var DatabaseManager
31
     */
32
    protected $dbal = null;
33
34
    /**
35
     * @param DatabaseManager $dbal
36
     */
37
    public function __construct(DatabaseManager $dbal)
38
    {
39
        $this->dbal = $dbal;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function getDatabase(string $database = null): Database
46
    {
47
        return $this->dbal->database($database);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function getTable(string $table, string $database = null): Table
54
    {
55
        return $this->dbal->database($database)->table($table);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function getSchema(string $table, string $database = null): AbstractTable
62
    {
63
        if (!isset($this->schemas[$database . '.' . $table])) {
64
            $schema = $this->getTable($table, $database)->getSchema();
65
66
            //We have to declare existed to prevent dropping existed schema
67
            $this->schemas[$database . '.' . $table] = $schema;
68
        }
69
70
        return $this->schemas[$database . '.' . $table];
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     *
76
     * @throws \Throwable
77
     */
78
    public function execute(array $operations)
79
    {
80
        /*
81
         * Executing operation per operation.
82
         */
83
        foreach ($operations as $operation) {
84
            if ($operation instanceof OperationInterface) {
85
                $operation->execute($this);
86
            } else {
87
                throw new CapsuleException(sprintf(
88
                    "Migration operation expected to be an instance of OperationInterface, '%s' given",
89
                    get_class($operation)
90
                ));
91
            }
92
        }
93
    }
94
}