|
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\UnquotedSubstitutionConstants; |
|
9
|
|
|
use Mhorninger\MySQLite\MethodRewriteConstants; |
|
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
|
|
|
return parent::run($query, $bindings, $callback); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
private function scanQueryForConstants($query) |
|
44
|
|
|
{ |
|
45
|
|
|
$reflection = new ReflectionClass(SubstitutionConstants::class); |
|
46
|
|
|
$constants = $reflection->getConstants(); |
|
47
|
|
|
$placeholders = array_keys($constants); |
|
48
|
|
|
foreach ($placeholders as $placeholder) { |
|
49
|
|
|
$searchFor = '/'.preg_quote($placeholder).'(?!\\(|\\w|\\))/'; |
|
50
|
|
|
$query = preg_replace($searchFor, "'".$constants[$placeholder]."'", $query); |
|
51
|
|
|
} |
|
52
|
|
|
$reflection = new ReflectionClass(UnquotedSubstitutionConstants::class); |
|
53
|
|
|
$methodConstants = $reflection->getConstants(); |
|
54
|
|
|
$placeholders = array_keys($methodConstants); |
|
55
|
|
|
foreach ($placeholders as $placeholder) { |
|
56
|
|
|
$query = str_replace($placeholder, $methodConstants[$placeholder], $query); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
return $query; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private function methodRewrite($query) |
|
63
|
|
|
{ |
|
64
|
|
|
foreach (array_keys(MethodRewriteConstants::METHOD_REPLACEMENTS) as $regex) { |
|
65
|
|
|
$query = preg_replace($regex, MethodRewriteConstants::METHOD_REPLACEMENTS[$regex], $query); |
|
66
|
|
|
} |
|
67
|
|
|
return $query; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|