| 1 |
<?php |
| 2 |
|
| 3 |
namespace WpFluent\QueryBuilder; |
| 4 |
|
| 5 |
class QueryObject |
| 6 |
{ |
| 7 |
/** |
| 8 |
* @var string |
| 9 |
*/ |
| 10 |
protected $sql; |
| 11 |
|
| 12 |
/** |
| 13 |
* @var \wpdb |
| 14 |
*/ |
| 15 |
protected $db; |
| 16 |
|
| 17 |
/** |
| 18 |
* @var array |
| 19 |
*/ |
| 20 |
protected $bindings = array(); |
| 21 |
|
| 22 |
public function __construct($sql, array $bindings) |
| 23 |
{ |
| 24 |
$this->sql = (string) $sql; |
| 25 |
|
| 26 |
$this->bindings = $bindings; |
| 27 |
|
| 28 |
global $wpdb; |
| 29 |
|
| 30 |
$this->db = $wpdb; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* @return string |
| 35 |
*/ |
| 36 |
public function getSql() |
| 37 |
{ |
| 38 |
return $this->sql; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* @return array |
| 43 |
*/ |
| 44 |
public function getBindings() |
| 45 |
{ |
| 46 |
return $this->bindings; |
| 47 |
} |
| 48 |
|
| 49 |
/** |
| 50 |
* Get the raw/bound sql |
| 51 |
* |
| 52 |
* @return string |
| 53 |
*/ |
| 54 |
public function getRawSql() |
| 55 |
{ |
| 56 |
return $this->interpolateQuery($this->sql, $this->bindings); |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Replaces any parameter placeholders in a query with the value of that |
| 61 |
* parameter. Useful for debugging. Assumes anonymous parameters from |
| 62 |
* $params are are in the same order as specified in $query |
| 63 |
* |
| 64 |
* Reference: http://stackoverflow.com/a/1376838/656489 |
| 65 |
* |
| 66 |
* @param string $query The sql query with parameter placeholders |
| 67 |
* @param array $params The array of substitution parameters |
| 68 |
* |
| 69 |
* @return string The interpolated query |
| 70 |
*/ |
| 71 |
protected function interpolateQuery($query, $params) |
| 72 |
{ |
| 73 |
$keys = $placeHolders = []; |
| 74 |
|
| 75 |
foreach ($params as $key => $value) { |
| 76 |
if (is_string($key)) { |
| 77 |
$keys[] = '/:' . $key . '/'; |
| 78 |
} else { |
| 79 |
$keys[] = '/[?]/'; |
| 80 |
} |
| 81 |
|
| 82 |
$placeHolders[] = $this->getPlaceHolder($value); |
| 83 |
} |
| 84 |
|
| 85 |
$query = preg_replace($keys, $placeHolders, $query, 1, $count); |
| 86 |
|
| 87 |
return $params ? $this->db->prepare($query, $params) : $query; |
| 88 |
} |
| 89 |
|
| 90 |
private function getPlaceHolder($value) |
| 91 |
{ |
| 92 |
$placeHolder = '%s'; |
| 93 |
|
| 94 |
if (is_int($value)) { |
| 95 |
$placeHolder = '%d'; |
| 96 |
} elseif (is_float($value)) { |
| 97 |
$placeHolder = '%f'; |
| 98 |
} |
| 99 |
|
| 100 |
return $placeHolder; |
| 101 |
} |
| 102 |
} |
| 103 |
|