Completed
Push — master ( d278b5...81f2b1 )
by Guillaume
02:18
created

MysqlDatabaseTable::getCollate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace Starkerxp\DatabaseChecker\Structure;
4
5
6
//@todo Manage data sync by option.
7
use Starkerxp\DatabaseChecker\Exception\TableHasNotColumnException;
8
use Starkerxp\DatabaseChecker\Exception\TableHasNotDefinedException;
9
10
class MysqlDatabaseTable implements DatabaseInterface
11
{
12
13
    private $table;
14
    /**
15
     * @var MysqlDatabaseColumn[]
16
     */
17
    private $columns = [];
18
19
    /**
20
     * @var MysqlDatabaseIndex[]
21
     */
22
    private $indexes = [];
23
24
    /**
25
     * @var string
26
     */
27
    private $collate;
28
29
    /**
30
     * DatabaseTableStructure constructor.
31
     *
32
     * @param $table
33
     *
34
     * @throws TableHasNotDefinedException
35
     */
36
    public function __construct($table)
37
    {
38
        if (empty($table)) {
39
            throw new TableHasNotDefinedException('');
40
        }
41
        $this->table = $table;
42
    }
43
44
    /**
45
     * @return string
46
     */
47
    public function getCollate()
48
    {
49
        return $this->collate;
50
    }
51
52
    /**
53
     * @param string $collate
54
     */
55
    public function setCollate($collate)
56
    {
57
        $this->collate = $collate;
58
    }
59
60
    public function addColumn(MysqlDatabaseColumn $column)
61
    {
62
        $column->setTable($this->getTable());
63
        $this->columns[$column->getName()] = $column;
64
    }
65
66
    /**
67
     * @return mixed
68
     */
69
    public function getTable()
70
    {
71
        return $this->table;
72
    }
73
74
    public function removeColumn($columnName)
75
    {
76
77
        unset($this->columns[$columnName]);
78
    }
79
80
    public function addIndex(array $columns, $indexName = '')
81
    {
82
        $this->addIndexType($indexName, 0, $columns);
83
    }
84
85
    /**
86
     * @param       $indexName
87
     * @param       $unique
88
     * @param array $columns
89
     */
90
    protected function addIndexType($indexName, $unique, array $columns)
91
    {
92
        if (empty($indexName)) {
93
            $indexName = ($unique ? 'UNI_' : 'IDX_') . md5(implode(',', $columns));
94
        }
95
        try {
96
            $index = new MysqlDatabaseIndex($indexName, $columns, $unique);
97
            $index->setTable($this->getTable());
98
            $this->indexes[$indexName] = $index;
99
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
100
101
        }
102
    }
103
104
    public function addPrimary(array $columnName)
105
    {
106
        $this->addIndexType('PRIMARY', 1, $columnName);
107
    }
108
109
    public function addUnique(array $columnName, $indexName = '')
110
    {
111
        $this->addIndexType($indexName, 1, $columnName);
112
    }
113
114
    /**
115
     * @param $indexName
116
     *
117
     * @return MysqlDatabaseIndex
118
     *
119
     * @throws \RuntimeException
120
     */
121
    public function getIndex($indexName)
122
    {
123
        if (null === $this->indexes[$indexName]) {
124
            throw new \RuntimeException('');
125
        }
126
127
        return $this->indexes[$indexName];
128
    }
129
130
    public function toArray()
131
    {
132
        $export = [];
133
        $export['columns'] = [];
134
        $columns = $this->getColumns();
135
        foreach ($columns as $column) {
136
            $export['columns'][] = $column->toArray();
137
        }
138
139
        $export['indexes'] = [];
140
        $indexes = $this->getIndexes();
141
        foreach ($indexes as $index) {
142
            $export['indexes'][] = $index->toArray();
143
        }
144
145
        return $export;
146
    }
147
148
    /**
149
     * @return MysqlDatabaseColumn[]
150
     */
151
    public function getColumns()
152
    {
153
        return $this->columns;
154
    }
155
156
    public function getIndexes()
157
    {
158
        return $this->indexes;
159
    }
160
161
    /**
162
     * @return array
163
     *
164
     * @throws TableHasNotColumnException
165
     */
166
    public function createStatement()
167
    {
168
        $modifications = [];
169
        $modifications[] = [sprintf('CREATE TABLE IF NOT EXISTS `%s`', $this->getTable())];
170
        $columns = $this->getColumns();
171
        if (!count($columns)) {
172
            throw new TableHasNotColumnException('');
173
        }
174
        foreach ($columns as $column) {
175
            try {
176
                if($this->getCollate() == ''){
177
                    $column->setCollate('');
178
                }
179
                $modifications[] = $column->createStatement();
180
            } catch (TableHasNotDefinedException $e) {
181
                continue;
182
            }
183
        }
184
        $indexes = $this->getIndexes();
185
        foreach ($indexes as $index) {
186
            try {
187
                $modifications[] = $index->createStatement();
188
            } catch (TableHasNotDefinedException $e) {
189
                continue;
190
            }
191
        }
192
193
        if (!$modifications = $this->formatStatements($modifications)) {
194
            return [];
195
        }
196
197
        return $this->formatCreateStatement($modifications);
198
199
    }
200
201
    /**
202
     * @param array $modificationsBetweenTable
203
     *
204
     * @return array
205
     */
206
    private function formatStatements(array $modificationsBetweenTable)
207
    {
208
        $statements = [];
209
        foreach ($modificationsBetweenTable as $modifications) {
210
            foreach ((array)$modifications as $modification) {
211
                $statements[] = $modification;
212
            }
213
        }
214
215
        return array_filter(array_unique($statements));
216
    }
217
218
    private function formatCreateStatement(array $modifications)
219
    {
220
        if (!$finalStatement = array_shift($modifications)) {
221
            return [];
222
        }
223
        $tmp = [];
224
        foreach ($modifications as $modification) {
225
            $tmp[] = trim(str_replace(['ALTER TABLE `' . $this->getTable() . '` ADD COLUMN', 'ALTER TABLE `' . $this->getTable() . '` ADD ', ';',], '', $modification));
226
        }
227
        $collate = $this->getCollate() == '' ? '' : sprintf("COLLATE='%s'", $this->getCollate());
228
229
        return [$finalStatement . '(' . implode(',', $tmp) . ')' . $collate . ';'];
230
    }
231
232
    /**
233
     *
234
     * @throws \RuntimeException
235
     */
236
    public function alterStatement()
237
    {
238
        $collate = $this->getCollate() == '' ? '' : sprintf("COLLATE='%s'", $this->getCollate());
239
        if ($collate == '') {
240
            throw new \RuntimeException('Not implemented');
241
        }
242
243
        return [sprintf('ALTER TABLE `%s` %s;', $this->getTable(), $collate)];
244
    }
245
246
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
247