1 | <?php |
||
2 | |||
3 | namespace Pixie\QueryBuilder; |
||
4 | |||
5 | use wpdb; |
||
6 | |||
7 | class QueryObject |
||
8 | { |
||
9 | /** |
||
10 | * @var string |
||
11 | */ |
||
12 | protected $sql; |
||
13 | |||
14 | /** |
||
15 | * @var mixed[] |
||
16 | */ |
||
17 | protected $bindings = []; |
||
18 | |||
19 | /** |
||
20 | * @var wpdb |
||
21 | */ |
||
22 | protected $dbInstance; |
||
23 | |||
24 | /** |
||
25 | * @param string $sql |
||
26 | * @param mixed[] $bindings |
||
27 | * @param wpdb $dbInstance |
||
28 | */ |
||
29 | public function __construct(string $sql, array $bindings, wpdb $dbInstance) |
||
30 | { |
||
31 | $this->sql = (string)$sql; |
||
32 | $this->bindings = $bindings; |
||
33 | $this->dbInstance = $dbInstance; |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * @return string |
||
38 | */ |
||
39 | public function getSql() |
||
40 | { |
||
41 | return $this->sql; |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * @return mixed[] |
||
46 | */ |
||
47 | public function getBindings() |
||
48 | { |
||
49 | return $this->bindings; |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * Get the raw/bound sql |
||
54 | * |
||
55 | * @return string |
||
56 | */ |
||
57 | public function getRawSql() |
||
58 | { |
||
59 | return $this->interpolateQuery($this->sql, $this->bindings); |
||
60 | } |
||
61 | |||
62 | /** |
||
63 | * Uses WPDB::prepare() to interpolate the query passed. |
||
64 | |||
65 | * |
||
66 | * @param string $query The sql query with parameter placeholders |
||
67 | * @param mixed[] $params The array of substitution parameters |
||
68 | * |
||
69 | * @return string The interpolated query |
||
70 | */ |
||
71 | protected function interpolateQuery($query, $params): string |
||
72 | { |
||
73 | // Only call this when we have valid params (avoids wpdb::prepare() incorrectly called error) |
||
74 | $value = empty($params) ? $query : $this->dbInstance->prepare($query, $params); |
||
75 | |||
76 | return is_string($value) ? $value : ''; |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
77 | } |
||
78 | } |
||
79 |