Skip to content

Commit 17d358c

Browse files
committed
Adding support for sortable
1 parent 8ba6a41 commit 17d358c

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
"mouf/database.dbconnection": "~2.0",
1818
"mouf/utils.common.conditioninterface": "~2.0",
1919
"mouf/utils.value.value-interface": "~1.0",
20-
"mouf/utils.common.paginable-interface": "~1.0"
20+
"mouf/utils.common.paginable-interface": "~1.0",
21+
"mouf/utils.common.sortable-interface": "~1.0"
2122
},
2223
"autoload": {
2324
"psr-0": {

src/Mouf/Database/QueryWriter/QueryResult.php

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,16 @@
1111
use Mouf\Utils\Value\ValueInterface;
1212

1313
use Mouf\Database\DBConnection\ConnectionInterface;
14+
use Mouf\Utils\Common\SortableInterface;
15+
use SQLParser\Node\NodeInterface;
16+
use SQLParser\Node\ColRef;
1417

1518
/**
1619
* A class that can execute a query and expose the results.
1720
*
1821
* @author David Negrier
1922
*/
20-
class QueryResult implements ArrayValueInterface, PaginableInterface {
23+
class QueryResult implements ArrayValueInterface, PaginableInterface, SortableInterface {
2124

2225
/**
2326
* The Select statement.
@@ -91,5 +94,49 @@ public function paginate($limit, $offset = 0) {
9194
$this->limit = $limit;
9295
$this->offset = $offset;
9396
}
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+
}
94116

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+
}
95142
}

0 commit comments

Comments
 (0)