-
Notifications
You must be signed in to change notification settings - Fork 0
/
Database.php
84 lines (64 loc) · 2.11 KB
/
Database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace FpDbTest;
use Exception;
use mysqli;
class Database implements DatabaseInterface
{
public const SKIP = '--skip--';
private array $handlers;
private mysqli $mysqli;
public function __construct(mysqli $mysqli)
{
$this->mysqli = $mysqli;
$this
->addHandlers(new ArrayPlaceholderHandler())
->addHandlers(new DecimalPlaceholderHandler())
->addHandlers(new FloatPlaceholderHandler())
->addHandlers(new EmptyPlaceholderHandler())
->addHandlers(new IdentifierPlaceholderHandler());
}
public function buildQuery(string $query, array $args = []): string
{
$queryParts = explode('?', $query);
if (count($queryParts) == 1) {
return $query;
}
$compiledQueryParts = [array_shift($queryParts)];
foreach ($queryParts as $i => $queryPart) {
$type = $queryPart[0];
$queryPart = substr($queryPart, 1);
$value = $args[$i];
foreach ($this->getHandlersForSpecifier($type) as $handler) {
$value = $handler->doHandle($value);
}
$compiledQueryParts[] = $value . $queryPart;
}
$compiledQuery = implode('', $compiledQueryParts);
return $this->handleConditionalBlocks($compiledQuery);
}
public function skip()
{
return self::SKIP;
}
public function getHandlers(): array
{
return $this->handlers;
}
public function addHandlers(AbstractPlaceholderHandler $handler): Database
{
$this->handlers[$handler->getSpecifier()][] = $handler;
return $this;
}
private function getHandlersForSpecifier(string $specifier): array
{
if (isset($this->handlers[$specifier])) {
return $this->handlers[$specifier];
}
throw new Exception("No handlers for specifier $specifier");
}
private function handleConditionalBlocks(string $query)
{
$query = preg_replace("/\{.*" . self::SKIP . ".*\}/", '', $query);
return str_replace(['{', '}'], '', $query);
}
}