Completed
Push — master ( 8a5ed3...6caf88 )
by Ivan
02:58
created

DB::driverName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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