|
11 | 11 | use Mouf\Utils\Value\ValueInterface;
|
12 | 12 |
|
13 | 13 | use Mouf\Database\DBConnection\ConnectionInterface;
|
| 14 | +use Mouf\Utils\Common\SortableInterface; |
| 15 | +use SQLParser\Node\NodeInterface; |
| 16 | +use SQLParser\Node\ColRef; |
14 | 17 |
|
15 | 18 | /**
|
16 | 19 | * A class that can execute a query and expose the results.
|
17 | 20 | *
|
18 | 21 | * @author David Negrier
|
19 | 22 | */
|
20 |
| -class QueryResult implements ArrayValueInterface, PaginableInterface { |
| 23 | +class QueryResult implements ArrayValueInterface, PaginableInterface, SortableInterface { |
21 | 24 |
|
22 | 25 | /**
|
23 | 26 | * The Select statement.
|
@@ -91,5 +94,49 @@ public function paginate($limit, $offset = 0) {
|
91 | 94 | $this->limit = $limit;
|
92 | 95 | $this->offset = $offset;
|
93 | 96 | }
|
| 97 | + |
| 98 | + /* (non-PHPdoc) |
| 99 | + * @see \Mouf\Utils\Common\SortableInterface::sort() |
| 100 | + */ |
| 101 | + public function sort($key, $direction = SortableInterface::ASC) { |
| 102 | + $result = $this->findColumnByKey($key); |
| 103 | + if ($result != null) { |
| 104 | + $columnObj = clone($result); |
| 105 | + if (method_exists($columnObj, "setAlias")) { |
| 106 | + $columnObj->setAlias(null); |
| 107 | + } |
| 108 | + $columnObj->setDirection($direction); |
| 109 | + } else { |
| 110 | + $columnObj = new ColRef(); |
| 111 | + $columnObj->setColumn($key); |
| 112 | + $columnObj->setDirection($direction); |
| 113 | + } |
| 114 | + $this->select->setOrder(array($columnObj)); |
| 115 | + } |
94 | 116 |
|
| 117 | + /** |
| 118 | + * Returns the object representing a column from the key passed in parameter. |
| 119 | + * It will first scan the column aliases to find if an alias match the key, then the column names, etc... |
| 120 | + * It will throw an exception if the column cannot be found. |
| 121 | + * |
| 122 | + * @param string $key |
| 123 | + * @return NodeInterface |
| 124 | + */ |
| 125 | + private function findColumnByKey($key) { |
| 126 | + $columns = $this->select->getColumns(); |
| 127 | + foreach ($columns as $column) { |
| 128 | + if (method_exists($column, "getAlias")) { |
| 129 | + $alias = $column->getAlias(); |
| 130 | + if ($alias === $key) { |
| 131 | + return $column; |
| 132 | + } |
| 133 | + } |
| 134 | + if ($column instanceof ColRef) { |
| 135 | + if ($column->getColumn() === $key) { |
| 136 | + return $column; |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + return null; |
| 141 | + } |
95 | 142 | }
|
|
0 commit comments