Completed
Push — master ( 0a3588...4a58a6 )
by Ivan
02:50
created

DB::parseSchema()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
namespace vakata\database;
4
5
use \vakata\collection\Collection;
6
use \vakata\database\schema\Table;
7
use \vakata\database\schema\TableQuery;
8
use \vakata\database\schema\TableQueryMapped;
9
use \vakata\database\schema\TableRelation;
10
11
/**
12
 * A database abstraction with support for various drivers (mySQL, postgre, oracle, msSQL, sphinx, and even PDO).
13
 */
14
class DB implements DBInterface
15
{
16
    /**
17
     * @var DriverInterface
18
     */
19
    protected $driver;
20
    /**
21
     * @var Table[]
22
     */
23
    protected $tables = [];
24
25
    /**
26
     * Create an instance.
27
     *
28
     * @param string $connectionString a driver instance or a connection string
29
     */
30 15
    public function __construct(string $connectionString)
31
    {
32
        $connection = [
33 15
            'orig' => $connectionString,
34
            'type' => null,
35
            'user' => null,
36
            'pass' => null,
37
            'host' => null,
38
            'port' => null,
39
            'name' => null,
40
            'opts' => []
41
        ];
42
        $aliases = [
43 15
            'my'        => 'mysql',
44
            'mysqli'    => 'mysql',
45
            'pg'        => 'postgre',
46
            'oci'       => 'oracle',
47
            'firebird'  => 'ibase'
48
        ];
49 15
        $temp = parse_url($connectionString);
50 15
        if ($temp === false || (isset($temp['query']) && strpos($temp['query'], 'regexparser=1') !== false)) {
51 6
            if (!preg_match(
52 6
                '(^
53
                    (?<scheme>.*?)://
54
                    (?:(?<user>.*?)(?:\:(?<pass>.*))?@)?
55
                    (?<host>[a-zа-я.\-_0-9=();:]+?) # added =();: for oracle and pdo configs
56
                    (?:\:(?<port>\d+))?
57
                    (?<path>/.+?)? # path is optional for oracle and pdo configs
58
                    (?:\?(?<query>.*))?
59
                $)xui',
60 6
                $connectionString,
61 6
                $temp
62
            )) {
63
                $temp = explode('://', $connectionString, 2);
64
                if (!preg_match('(^[a-z0-9_]+$)i', $temp[0])) {
65
                    throw new DBException('Could not parse connection string');
66
                }
67
                $temp = [
68
                    'scheme' => $temp[0]
69
                ];
70
            }
71
        }
72 15
        $connection['type'] = isset($temp['scheme']) && strlen($temp['scheme']) ? $temp['scheme'] : null;
73 15
        $connection['user'] = isset($temp['user']) && strlen($temp['user']) ? $temp['user'] : null;
74 15
        $connection['pass'] = isset($temp['pass']) && strlen($temp['pass']) ? $temp['pass'] : null;
75 15
        $connection['host'] = isset($temp['host']) && strlen($temp['host']) ? $temp['host'] : null;
76 15
        $connection['name'] = isset($temp['path']) && strlen($temp['path']) ? trim($temp['path'], '/') : null;
77 15
        $connection['port'] = isset($temp['port']) && (int)$temp['port'] ? (int)$temp['port'] : null;
78 15
        if (isset($temp['query']) && strlen($temp['query'])) {
79 15
            parse_str($temp['query'], $connection['opts']);
80
        }
81
        // create the driver
82 15
        $connection['type'] = $aliases[$connection['type']] ?? $connection['type'];
83 15
        $tmp = '\\vakata\\database\\driver\\'.strtolower($connection['type']).'\\Driver';
84 15
        if (!class_exists($tmp)) {
85
            throw new DBException('Unknown DB backend');
86
        }
87 15
        $this->driver = new $tmp($connection);
88 15
    }
89
90
    public function driver(): DriverInterface
91
    {
92
        return $this->driver;
93
    }
94
95
    /**
96
     * Prepare a statement.
97
     * Use only if you need a single query to be performed multiple times with different parameters.
98
     *
99
     * @param string $sql the query to prepare - use `?` for arguments
100
     * @return StatementInterface the prepared statement
101
     */
102 1
    public function prepare(string $sql) : StatementInterface
103
    {
104 1
        return $this->driver->prepare($sql);
105
    }
106
    /**
107
     * Test the connection
108
     *
109
     * @return bool
110
     */
111 1
    public function test() : bool
112
    {
113 1
        return $this->driver->test();
114
    }
115 27
    protected function expand(string $sql, $par = null) : array
116
    {
117 27
        $new = '';
118 27
        $par = array_values($par);
119 27
        if (substr_count($sql, '?') === 2 && !is_array($par[0])) {
120 3
            $par = [ $par ];
121
        }
122 27
        $parts = explode('??', $sql);
123 27
        $index = 0;
124 27
        foreach ($parts as $part) {
125 27
            $tmp = explode('?', $part);
126 27
            $new .= $part;
127 27
            $index += count($tmp) - 1;
128 27
            if (isset($par[$index])) {
129 27
                if (!is_array($par[$index])) {
130
                    $par[$index] = [ $par[$index] ];
131
                }
132 27
                $params = $par[$index];
133 27
                array_splice($par, $index, 1, $params);
134 27
                $index += count($params);
135 27
                $new .= implode(',', array_fill(0, count($params), '?'));
136
            }
137
        }
138 27
        return [ $new, $par ];
139
    }
140
    /**
141
     * Run a query (prepare & execute).
142
     * @param string      $sql  SQL query
143
     * @param mixed  $par parameters (optional)
144
     * @return ResultInterface the result of the execution
145
     */
146 166
    public function query(string $sql, $par = null) : ResultInterface
147
    {
148 166
        $par = isset($par) ? (is_array($par) ? $par : [$par]) : [];
149 166
        if (strpos($sql, '??') && count($par)) {
150 27
            list($sql, $par) = $this->expand($sql, $par);
151
        }
152 166
        return $this->driver->prepare($sql)->execute($par);
153
    }
154
    /**
155
     * Run a SELECT query and get an array-like result.
156
     * When using `get` the data is kept in the database client and fetched as needed (not in PHP memory as with `all`)
157
     *
158
     * @param string   $sql      SQL query
159
     * @param array    $par      parameters
160
     * @param string   $key      column name to use as the array index
161
     * @param bool     $skip     do not include the column used as index in the value (defaults to `false`)
162
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
163
     *
164
     * @return Collection the result of the execution
165
     */
166 160
    public function get(string $sql, $par = null, string $key = null, bool $skip = false, bool $opti = true): Collection
167
    {
168 160
        $coll = Collection::from($this->query($sql, $par));
169 160
        if (($keys = $this->driver->option('mode')) && in_array($keys, ['strtoupper', 'strtolower'])) {
170 1
            $coll->map(function ($v) use ($keys) {
171 1
                $new = [];
172 1
                foreach ($v as $k => $vv) {
173 1
                    $new[call_user_func($keys, $k)] = $vv;
174
                }
175 1
                return $new;
176 1
            });
177
        }
178 160
        if ($key !== null) {
179 2
            $coll->mapKey(function ($v) use ($key) {
180 2
                return $v[$key];
181 2
            });
182
        }
183 160
        if ($skip) {
184 2
            $coll->map(function ($v) use ($key) {
185 2
                unset($v[$key]);
186 2
                return $v;
187 2
            });
188
        }
189 160
        if ($opti) {
190 67
            $coll->map(function ($v) {
191 67
                return count($v) === 1 ? current($v) : $v;
192 67
            });
193
        }
194 160
        return $coll;
195
    }
196
    /**
197
     * Run a SELECT query and get a single row
198
     * @param string   $sql      SQL query
199
     * @param array    $par      parameters
200
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
201
     * @return mixed the result of the execution
202
     */
203 63
    public function one(string $sql, $par = null, bool $opti = true)
204
    {
205 63
        return $this->get($sql, $par, null, false, $opti)->value();
206
    }
207
    /**
208
     * Run a SELECT query and get an array
209
     * @param string   $sql      SQL query
210
     * @param array    $par      parameters
211
     * @param string   $key      column name to use as the array index
212
     * @param bool     $skip     do not include the column used as index in the value (defaults to `false`)
213
     * @param bool     $opti     if a single column is returned - do not use an array wrapper (defaults to `true`)
214
     * @return array the result of the execution
215
     */
216 6
    public function all(string $sql, $par = null, string $key = null, bool $skip = false, bool $opti = true) : array
217
    {
218 6
        return $this->get($sql, $par, $key, $skip, $opti)->toArray();
219
    }
220
    /**
221
     * Begin a transaction.
222
     * @return $this
223
     */
224 1
    public function begin() : DBInterface
225
    {
226 1
        if (!$this->driver->begin()) {
227
            throw new DBException('Could not begin');
228
        }
229 1
        return $this;
230
    }
231
    /**
232
     * Commit a transaction.
233
     * @return $this
234
     */
235 1
    public function commit() : DBInterface
236
    {
237 1
        if (!$this->driver->commit()) {
238
            throw new DBException('Could not commit');
239
        }
240 1
        return $this;
241
    }
242
    /**
243
     * Rollback a transaction.
244
     * @return $this
245
     */
246 1
    public function rollback() : DBInterface
247
    {
248 1
        if (!$this->driver->rollback()) {
249
            throw new DBException('Could not rollback');
250
        }
251 1
        return $this;
252
    }
253
    /**
254
     * Get the current driver name (`"mysql"`, `"postgre"`, etc).
255
     * @return string the current driver name
256
     */
257 16
    public function driverName() : string
258
    {
259 16
        return array_reverse(explode('\\', get_class($this->driver)))[1];
260
    }
261
    /**
262
     * Get an option from the driver
263
     *
264
     * @param string $key     the option name
265
     * @param mixed  $default the default value to return if the option key is not defined
266
     * @return mixed the option value
267
     */
268 76
    public function driverOption(string $key, $default = null)
269
    {
270 76
        return $this->driver->option($key, $default);
271
    }
272
273 156
    public function definition(string $table, bool $detectRelations = true) : Table
274
    {
275 156
        return isset($this->tables[$table]) ?
276
            $this->tables[$table] :
277 156
            $this->driver->table($table, $detectRelations);
278
    }
279
    /**
280
     * Parse all tables from the database.
281
     * @return $this
282
     */
283
    public function parseSchema()
284
    {
285
        $this->tables = $this->driver->tables();
286
        return $this;
287
    }
288
    /**
289
     * Get the full schema as an array that you can serialize and store
290
     * @return array
291
     */
292
    public function getSchema($asPlainArray = true)
293
    {
294 4
        return !$asPlainArray ? $this->tables : array_map(function ($table) {
295
            return [
296
                'name' => $table->getName(),
297
                'pkey' => $table->getPrimaryKey(),
298
                'comment' => $table->getComment(),
299
                'columns' => array_map(function ($column) {
300
                    return [
301
                        'name' => $column->getName(),
302
                        'type' => $column->getType(),
303
                        'length' => $column->getLength(),
304
                        'comment' => $column->getComment(),
305
                        'values' => $column->getValues(),
306
                        'default' => $column->getDefault(),
307
                        'nullable' => $column->isNullable()
308
                    ];
309
                }, $table->getFullColumns()),
310
                'relations' => array_map(function ($rel) {
311
                    $relation = clone $rel;
312
                    $relation = (array)$relation;
313
                    $relation['table'] = $rel->table->getName();
314
                    if ($rel->pivot) {
315
                        $relation['pivot'] = $rel->pivot->getName();
316
                    }
317
                    return $relation;
318
                }, $table->getRelations())
319
            ];
320 4
        }, $this->tables);
321
    }
322
    /**
323
     * Load the schema data from a schema definition array (obtained from getSchema)
324
     * @param  array        $data the schema definition
325
     * @return $this
326
     */
327
    public function setSchema(array $data)
328
    {
329
        foreach ($data as $tableData) {
330
            $this->tables[$tableData['name']] = (new Table($tableData['name']))
331
                        ->setPrimaryKey($tableData['pkey'])
332
                        ->setComment($tableData['comment'])
333
                        ->addColumns($tableData['columns']);
334
        }
335
        foreach ($data as $tableData) {
336
            $table = $this->definition($tableData['name']);
337
            foreach ($tableData['relations'] as $relationName => $relationData) {
338
                $relationData['table'] = $this->definition($relationData['table']);
339
                if ($relationData['pivot']) {
340
                    $relationData['pivot'] = $this->definition($relationData['pivot']);
341
                }
342
                $table->addRelation(new TableRelation(
343
                    $relationData['name'],
344
                    $relationData['table'],
345
                    $relationData['keymap'],
346
                    $relationData['many'],
347
                    $relationData['pivot'] ?? null,
348
                    $relationData['pivot_keymap'],
349
                    $relationData['sql'],
350
                    $relationData['par']
351
                ));
352
            }
353
        }
354
        return $this;
355
    }
356
357
    /**
358
     * Initialize a table query
359
     * @param string $table the table to query
360
     * @return TableQuery
361
     */
362 156
    public function table(string $table, bool $mapped = false)
363
    {
364 156
        return $mapped ?
365 80
            new TableQueryMapped($this, $this->definition($table)) :
366 156
            new TableQuery($this, $this->definition($table));
367
    }
368 148
    public function __call($method, $args)
369
    {
370 148
        return $this->table($method, $args[0] ?? false);
371
    }
372
}
373