Completed
Branch feature/pre-split (42159e)
by Anton
05:36
created

SQLiteReference::compare()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 8
nc 6
nop 1
dl 0
loc 12
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Database\Drivers\SQLite\Schemas;
10
11
use Spiral\Database\Entities\Driver;
12
use Spiral\Database\Schemas\Prototypes\AbstractReference;
13
use Spiral\Database\Schemas\ReferenceInterface;
14
15
class SQLiteReference extends AbstractReference
16
{
17
    /**
18
     * In SQLite we have no predictable name.
19
     *
20
     * @return string
21
     */
22
    public function getName(): string
23
    {
24
        return $this->tablePrefix . $this->table . '_' . $this->column . '_fk';
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function sqlStatement(Driver $driver): string
31
    {
32
        $statement = [];
33
34
        $statement[] = 'FOREIGN KEY';
35
        $statement[] = '(' . $driver->identifier($this->column) . ')';
36
37
        $statement[] = 'REFERENCES ' . $driver->identifier($this->foreignTable);
38
        $statement[] = '(' . $driver->identifier($this->foreignKey) . ')';
39
40
        $statement[] = "ON DELETE {$this->deleteRule}";
41
        $statement[] = "ON UPDATE {$this->updateRule}";
42
43
        return implode(' ', $statement);
44
    }
45
46
    /**
47
     * Name insensitive compare.
48
     *
49
     * @param ReferenceInterface $initial
50
     *
51
     * @return bool
52
     */
53
    public function compare(ReferenceInterface $initial): bool
54
    {
55
        if (parent::compare($initial)) {
56
            return true;
57
        }
58
59
        return $this->getColumn() == $initial->getColumn()
60
            && $this->getForeignTable() == $initial->getForeignTable()
61
            && $this->getForeignKey() == $initial->getForeignKey()
62
            && $this->getUpdateRule() == $initial->getUpdateRule()
63
            && $this->getDeleteRule() == $initial->getDeleteRule();
64
    }
65
66
    /**
67
     * @param string $table
68
     * @param string $tablePrefix
69
     * @param array  $schema
70
     *
71
     * @return SQLiteReference
72
     */
73
    public static function createInstance(string $table, string $tablePrefix, array $schema): self
74
    {
75
        $reference = new self($table, $tablePrefix, $schema['id']);
76
77
        $reference->column = $schema['from'];
78
79
        $reference->foreignTable = $schema['table'];
80
        $reference->foreignKey = $schema['to'];
81
82
        //In SQLLite we have to work with pre-defined reference names
83
        $reference->name = $reference->getName();
84
85
        $reference->deleteRule = $schema['on_delete'];
86
        $reference->updateRule = $schema['on_update'];
87
88
        return $reference;
89
    }
90
}
91