Skip to content

Commit

Permalink
API Create sortRaw() method to handle raw SQL
Browse files Browse the repository at this point in the history
  • Loading branch information
emteknetnz committed Nov 30, 2022
1 parent 7860e46 commit 9d86ee1
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 20 deletions.
101 changes: 81 additions & 20 deletions src/ORM/DataList.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Exception;
use InvalidArgumentException;
use LogicException;
use SilverStripe\ORM\Connect\MySQLDatabase;

/**
* Implements a "lazy loading" DataObjectSet.
Expand Down Expand Up @@ -321,46 +322,106 @@ public function distinct($value)
* @param string|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped.
* @return static
*/
public function sort()
public function sort(...$args)
{
$count = func_num_args();
return $this->sortInner(false, $args);
}

/**
* The same as sort(), though allows raw SQL to be used for sorting
*
* Return a new DataList instance as a copy of this data list with the sort
* order set.
*
* @see SS_List::sort()
* @see SQLSelect::orderby
* @example $list = $list->sort('Name'); // default ASC sorting
* @example $list = $list->sort('Mod(ID, 3) ASC, Name ASC'); // Raw SQL sort
* @example $list = $list->sort('Name', 'ASC');
* @example $list = $list->sort(array('Name'=>'ASC', 'Age'=>'DESC'));
*
* @param string|array Escaped SQL statement. If passed as array, all keys and values are assumed to be escaped.
* @return static
*/
public function sortRaw(...$args)
{
return $this->sortInner(true, $args);
}

private function validateDirection(string $direction): void
{
$dir = strtolower($direction);
if ($dir !== 'asc' && $dir !== 'desc') {
throw new InvalidArgumentException('Second argument to sort must be either ASC or DESC');
}
}

private function validateColumnNotRawSQL(string $column): void
{
// If column is surronded by backticks, then it's not raw sql
// Backticks are to allow the use of non-standard characters for column names in mysql
if ((DB::get_conn() instanceof MySQLDatabase) && preg_match('#^`[^`]*`$#', $column)) {
return;
}
// Look for non-alphanumeric characters in the column name
// Using this method rather than ^[^a-zA-Z0-9_]$ to account for column names including macrons etc
if (preg_match('#[\(\)\[\]{}\+\-\*/=\:\?\\;|&\'"`<>^%, ]#', $column)) {
throw new InvalidArgumentException('Raw SQL cannot be used for sort(), use sortRaw() instead');
}
}

private function sortInner(bool $allowRawSql, array $args)
{
$count = count($args);
if ($count == 0) {
return $this;
}

if ($count > 2) {
throw new InvalidArgumentException('This method takes zero, one or two arguments');
}

if ($count == 2) {
$col = null;
$dir = null;
list($col, $dir) = func_get_args();

// Validate direction
if (!in_array(strtolower($dir ?? ''), ['desc', 'asc'])) {
user_error('Second argument to sort must be either ASC or DESC');
}

$sort = [$col => $dir];
list($column, $direction) = $args;
$sort = [$column => $direction];
} else {
$sort = func_get_arg(0);
$sort = $args[0];
// if $sort is string and not allowing raw sql, convert string to array to allow for validation
if (is_string($sort) && !$allowRawSql) {
$newSort = [];
// making the assumption here there are no commas in column names
// if there are, change the column name to something more sensible
foreach (explode(',', $sort) as $colDir) {
// using regex instead of explode(' ') in case column name includes spaces
if (preg_match('/^(.+) (asc|desc)$/i', trim($colDir), $matches)) {
list($column, $direction) = [$matches[1], $matches[2]];
} else {
list($column, $direction) = [$colDir, 'ASC'];
}
$newSort[$column] = $direction;
}
$sort = $newSort;
}
}
// validation
if (is_array($sort)) {
foreach ($sort as $column => $direction) {
if (!$allowRawSql) {
$this->validateColumnNotRawSQL($column);
}
$this->validateDirection($direction);
}
}

return $this->alterDataQuery(function (DataQuery $query, DataList $list) use ($sort) {

if (is_string($sort) && $sort) {
if (false !== stripos($sort ?? '', ' asc') || false !== stripos($sort ?? '', ' desc')) {
//if (preg_match('/^(.+) (asc|desc)$/i', $sort)) {
$query->sort($sort);
} else {
$list->applyRelation($sort, $column, true);
$query->sort($column, 'ASC');
}
} elseif (is_array($sort)) {
// sort(array('Name'=>'desc'));
$query->sort(null, null); // wipe the sort

// Wipe the sort
$query->sort(null, null);
foreach ($sort as $column => $direction) {
// Convert column expressions to SQL fragment, while still allowing the passing of raw SQL
// fragments.
Expand Down
1 change: 1 addition & 0 deletions src/ORM/DataQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,7 @@ public function whereAny($filter)
* @param string $direction Direction ("ASC" or "DESC", escaped SQL statement)
* @param bool $clear Clear existing values
* @return $this
*
*/
public function sort($sort = null, $direction = null, $clear = true)
{
Expand Down

0 comments on commit 9d86ee1

Please sign in to comment.