According to the RQL specification, sort()
requires a list of properties prepended with a +
or -
, not a property followed by a direction. The current parser does a great job of allowing this functionality, no complaints there, but the sort()
description in QueryInterface.php
is misleading. Something akin to the following might be better:
/**
* @param string $fields,... List of fields, each prefixed with <+|->
*
* @return mixed
*/
public function sort(/* ... */);
...and here is one possible implementation:
/**
* {@inheritdoc}
*/
public function sort(/* ... */)
{
$fields = func_get_args();
$out = array();
// Note that + must be URL encoded as %2B
foreach( $fields as $field ) {
switch( $field[0] ) {
case '+' : array_push($out, substr($field, 1) . ' ASC' ); break;
case '-' : array_push($out, substr($field, 1) . ' DESC' ); break;
default: throw new \Exception("Must specify valid sort order for field {$field}"); break;
}
}
$out = implode( ', ', $out );
// And just for debugging...
print_r( $out );
exit;
}
Personally, I like implementing sorting as sort($field, $direction = false)
, where $direction
indicates whether the sorting should be reversed (i.e. DESC
). This works great with the pipe/ajax functionality of the SmartTable module for AngularJS. (However, much like the suggested implementation described in QueryInterface.php
, my implementation does not follow RQL spec.)
Here it is, if anyone out there is looking for more examples:
public function sort($field, $direction = false)
{
// protected function wrapTable() turns objects.title into `objects`.title
// It is meant for resolving ambiguity in joins by verifying against a list of allowed tables
// e.g. foobar.title would not be allowed, b/c table `foobar` is not assoc. with the current entity
$field = $this->wrapTable( $field );
$direction = filter_var($direction, FILTER_VALIDATE_BOOLEAN);
$direction = $direction ? 'DESC' : 'ASC';
array_push( $this->order, "{$field} {$direction}" );
// ...and then I retrieve the order with $queriable->get_order();
// Of course, currently, I'm limited to sorting by one field at a time
}
I'm using PHP ActiveRecord in my project. I've written a QueryInterface implementation for it, which generates an $options['conditions']
array. I'd be happy to add it to the project as an example. I've never done a pull request before, but let me know if you are interested, and I'll figure out how to do it. Cheers!