|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* @package Framework\DB |
|
5
|
|
|
* @author Anton Romanov |
|
6
|
|
|
* @copyright Copyright (c) 2015-2016, Anton Romanov |
|
7
|
|
|
* @link http://cadmium-cms.com |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace DB { |
|
11
|
|
|
|
|
12
|
|
|
abstract class Query { |
|
13
|
|
|
|
|
14
|
|
|
protected $query = ''; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Get a field/table name |
|
18
|
|
|
*/ |
|
19
|
|
|
|
|
20
|
|
|
protected function getName(string $name) : string { |
|
21
|
|
|
|
|
22
|
|
|
return preg_replace('/[^a-zA-Z0-9_]/', '_', trim($name)); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Get a field value |
|
27
|
|
|
*/ |
|
28
|
|
|
|
|
29
|
|
|
protected function getValue(string $value) : string { |
|
30
|
|
|
|
|
31
|
|
|
return ('\'' . addslashes($value) . '\''); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Get a field sorting direction |
|
36
|
|
|
*/ |
|
37
|
|
|
|
|
38
|
|
|
protected function getDirection(string $direction) : string { |
|
39
|
|
|
|
|
40
|
|
|
return ((strtoupper($direction) !== 'DESC') ? 'ASC' : 'DESC'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Convert a data array to a string |
|
45
|
|
|
*/ |
|
46
|
|
|
|
|
47
|
|
|
protected function getString($source = null, string $pattern = '', string $separator = '') : string { |
|
48
|
|
|
|
|
49
|
|
|
if (!is_array($source)) return (is_scalar($source) ? strval($source) : ''); |
|
50
|
|
|
|
|
51
|
|
|
$regexs = ['key' => '/\^([a-z]+)/', 'value' => '/\$([a-z]+)/']; $matches = ['key' => [], 'value' => []]; |
|
52
|
|
|
|
|
53
|
|
|
$parsers = ['name' => 'getName', 'value' => 'getValue', 'direction' => 'getDirection']; $output = []; $count = 0; |
|
54
|
|
|
|
|
55
|
|
|
# Parse pattern |
|
56
|
|
|
|
|
57
|
|
|
foreach ($regexs as $name => $regex) preg_match($regex, $pattern, $matches[$name]); |
|
58
|
|
|
|
|
59
|
|
|
# Process replacements |
|
60
|
|
|
|
|
61
|
|
|
foreach ($source as $key => $value) if (is_scalar($value)) { |
|
62
|
|
|
|
|
63
|
|
|
$output[$count] = $pattern; $item = &$output[$count++]; |
|
64
|
|
|
|
|
65
|
|
|
foreach ($matches as $name => $match) if (isset($match[1]) && isset($parsers[$match[1]])) { |
|
66
|
|
|
|
|
67
|
|
|
$item = str_replace($match[0], [$this, $parsers[$match[1]]]($$name), $item); |
|
68
|
|
|
} |
|
69
|
|
|
}; |
|
70
|
|
|
|
|
71
|
|
|
# ------------------------ |
|
72
|
|
|
|
|
73
|
|
|
return implode($separator, $output); |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* Convert the object to a string |
|
78
|
|
|
*/ |
|
79
|
|
|
|
|
80
|
|
|
public function __toString() : string { |
|
81
|
|
|
|
|
82
|
|
|
return $this->query; |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|