MySQLiteConnection   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
c 1
b 0
f 0
dl 0
loc 59
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A methodRewrite() 0 7 2
A __construct() 0 6 1
A scanQueryForConstants() 0 17 3
A run() 0 10 2
1
<?php
2
3
namespace Mhorninger\SQLite;
4
5
use ReflectionClass;
6
use Mhorninger\MySQLite\MySQLite;
7
use Mhorninger\MySQLite\SubstitutionConstants;
8
use Mhorninger\MySQLite\MethodRewriteConstants;
9
use Mhorninger\MySQLite\UnquotedSubstitutionConstants;
10
11
class MySQLiteConnection extends \Illuminate\Database\SQLiteConnection
12
{
13
    const ESCAPE_CHARS = ['`', '[', '"'];
14
15
    /**
16
     * Create a new database connection instance.
17
     *
18
     * @param  \PDO|\Closure     $pdo
19
     * @param  string   $database
20
     * @param  string   $tablePrefix
21
     * @param  array    $config
22
     * @return void
23
     */
24
    public function __construct($pdo, $database = '', $tablePrefix = '', array $config = [])
25
    {
26
        parent::__construct($pdo, $database, $tablePrefix, $config);
27
        //Make sure the PDO is actually a PDO and not a closure.
28
        $this->pdo = $this->getPdo();
29
        $this->pdo = MySQLite::createFunctions($this->pdo);
30
    }
31
32
    public function run($query, $bindings, \Closure $callback)
33
    {
34
        //Skip on inserts.
35
        $insertRegex = '/INSERT INTO.*?;/';
36
        if (0 == preg_match($insertRegex, $query)) {
37
            $query = $this->methodRewrite($query);
38
            $query = $this->scanQueryForConstants($query);
39
        }
40
41
        return parent::run($query, $bindings, $callback);
42
    }
43
44
    private function scanQueryForConstants($query)
45
    {
46
        $reflection = new ReflectionClass(SubstitutionConstants::class);
47
        $constants = $reflection->getConstants();
48
        $placeholders = array_keys($constants);
49
        foreach ($placeholders as $placeholder) {
50
            $searchFor = '/'.preg_quote($placeholder).'(?!\\(|\\w|\\))/';
51
            $query = preg_replace($searchFor, "'".$constants[$placeholder]."'", $query);
52
        }
53
        $reflection = new ReflectionClass(UnquotedSubstitutionConstants::class);
54
        $methodConstants = $reflection->getConstants();
55
        $placeholders = array_keys($methodConstants);
56
        foreach ($placeholders as $placeholder) {
57
            $query = str_replace($placeholder, $methodConstants[$placeholder], $query);
58
        }
59
60
        return $query;
61
    }
62
63
    private function methodRewrite($query)
64
    {
65
        foreach (array_keys(MethodRewriteConstants::METHOD_REPLACEMENTS) as $regex) {
66
            $query = preg_replace($regex, MethodRewriteConstants::METHOD_REPLACEMENTS[$regex], $query);
67
        }
68
69
        return $query;
70
    }
71
}
72