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) {
52 $v = implode(", ", $v);
61 * Get the query params
64 function getParams() {
78 * @return \pq\Query\Writer
82 $this->params
= array();
83 $this->types
= array();
88 * Append to the query string
89 * @return \pq\Query\Writer
92 if (strlen($this->query
)) {
95 $this->query
.= array_reduce(func_get_args(), array($this, "reduce"));
100 * Write a param placeholder and push the param onto the param list
101 * @param mixed $param
102 * @param string $type
105 function param($param, $type = null) {
106 if ($param instanceof ExpressibleInterface
) {
107 $param = $param->get();
109 if ($param instanceof Expr
) {
110 return (string) $param;
113 $this->params
[] = $param;
114 $this->types
[] = $type;
116 return "\$".count($this->params
);
120 * Write nested AND/OR criteria
121 * @param array $criteria
122 * @return \pq\Query\Writer
124 function criteria(array $criteria) {
125 if ((list($left, $right) = each($criteria))) {
127 if (is_array($right)) {
128 $this->criteria($right);
130 $this->write("(", $left, $this->param($right), ")");
132 while ((list($left, $right) = each($criteria))) {
133 $this->write(is_int($left) && is_array($right) ?
"OR" : "AND");
134 if (is_array($right)) {
135 $this->criteria($right);
137 $this->write("(", $left, $this->param($right), ")");