6 * A very simple query writer used by \pq\Gateway
8 class Writer
implements WriterInterface
26 * @param string $query initial query string
27 * @param array $params intial set of params
28 * @param array $types the types of the params
30 function __construct($query = "", array $params = array(), array $types = array()) {
31 $this->query
= $query;
32 $this->params
= $params;
33 $this->types
= $types;
37 * Get the query string
40 function __toString() {
45 * Reduce arguments to write()
50 protected function reduce($q, $v) {
51 return $q . " " . (is_array($v) ?
implode(", ", $v) : $v);
55 * Get the query params
58 function getParams() {
72 * @return \pq\Query\Writer
76 $this->params
= array();
77 $this->types
= array();
82 * Append to the query string
83 * @return \pq\Query\Writer
86 $this->query
.= array_reduce(func_get_args(), array($this, "reduce"));
91 * Write a param placeholder and push the param onto the param list
96 function param($param, $type = null) {
97 if ($param instanceof ExpressibleInterface
) {
98 $param = $param->get();
100 if ($param instanceof Expr
) {
101 return (string) $param;
104 $this->params
[] = $param;
105 $this->types
[] = $type;
107 return "\$".count($this->params
);
111 * Write nested AND/OR criteria
112 * @param array $criteria
113 * @return \pq\Query\Writer
115 function criteria(array $criteria) {
116 if ((list($left, $right) = each($criteria))) {
118 if (is_array($right)) {
119 $this->criteria($right);
121 $this->write("(", $left, $this->param($right), ")");
123 while ((list($left, $right) = each($criteria))) {
124 $this->write(is_int($left) && is_array($right) ?
"OR" : "AND");
125 if (is_array($right)) {
126 $this->criteria($right);
128 $this->write("(", $left, $this->param($right), ")");