61589c3a1cce081006e4b23793cf4b0d9b0bdfde
[m6w6/pq-gateway] / lib / pq / Query / Writer.php
1 <?php
2
3 namespace pq\Query;
4
5 /**
6 * A very simple query writer used by \pq\Gateway
7 */
8 class Writer
9 {
10 /**
11 * @var string
12 */
13 protected $query;
14
15 /**
16 * @var array
17 */
18 protected $params;
19
20 /**
21 * @var array
22 */
23 protected $types;
24
25 /**
26 * @param string $query initial query string
27 * @param array $params intial set of params
28 * @param array $types the types of the params
29 */
30 function __construct($query = "", array $params = array(), array $types = array()) {
31 $this->query = $query;
32 $this->params = $params;
33 $this->types = $types;
34 }
35
36 /**
37 * Get the query string
38 * @return string
39 */
40 function __toString() {
41 return $this->query;
42 }
43
44 /**
45 * Get the query params
46 * @return array
47 */
48 function getParams() {
49 return $this->params;
50 }
51
52 /**
53 * Get the param types
54 * @return array
55 */
56 function getTypes() {
57 return $this->types;
58 }
59
60 /**
61 * Reset
62 * @return \pq\Query\Writer
63 */
64 function reset() {
65 $this->query = "";
66 $this->params = array();
67 $this->types = array();
68 return $this;
69 }
70
71 /**
72 * Append to the query string
73 * @return \pq\Query\Writer
74 */
75 function write() {
76 $this->query .= array_reduce(func_get_args(), function($q, $v) {
77 return $q . " " . (is_array($v) ? implode(", ", $v) : $v);
78 });
79 return $this;
80 }
81
82 /**
83 * Write a param placeholder and push the param onto the param list
84 * @param mixed $param
85 * @param string $type
86 * @return string
87 */
88 function param($param, $type = null) {
89 if ($param instanceof Expr) {
90 return (string) $param;
91 }
92 $this->params[] = $param;
93 $this->types[] = $type;
94 return "\$".count($this->params);
95 }
96
97 /**
98 * Execute the query through \pq\Connection::execParams($this, $this->params, $this->types)
99 * @param \pq\Connection $c
100 * @return \pq\Result
101 */
102 function exec(\pq\Connection $c) {
103 return $c->execParams($this, $this->params, $this->types);
104 }
105 }