Commit 158eec4f authored by Alexander Butenko's avatar Alexander Butenko Committed by GitHub

Merge pull request #601 from thingNumber1/patch-1

Adding ORDER BY REGEXP possibilites
parents 72d231de dd37055b
...@@ -1080,16 +1080,16 @@ class MysqliDb ...@@ -1080,16 +1080,16 @@ class MysqliDb
/** /**
* This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries. * This method allows you to specify multiple (method chaining optional) ORDER BY statements for SQL queries.
* *
* @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc'); * @uses $MySqliDb->orderBy('id', 'desc')->orderBy('name', 'desc', '^[a-z]')->orderBy('name', 'desc');
* *
* @param string $orderByField The name of the database field. * @param string $orderByField The name of the database field.
* @param string $orderByDirection Order direction. * @param string $orderByDirection Order direction.
* @param array $customFields Fieldset for ORDER BY FIELD() ordering * @param mixed $customFieldsOrRegExp Array with fieldset for ORDER BY FIELD() ordering or string with regular expresion for ORDER BY REGEXP ordering
* *
* @throws Exception * @throws Exception
* @return MysqliDb * @return MysqliDb
*/ */
public function orderBy($orderByField, $orderbyDirection = "DESC", $customFields = null) public function orderBy($orderByField, $orderbyDirection = "DESC", $customFieldsOrRegExp = null)
{ {
$allowedDirection = Array("ASC", "DESC"); $allowedDirection = Array("ASC", "DESC");
$orderbyDirection = strtoupper(trim($orderbyDirection)); $orderbyDirection = strtoupper(trim($orderbyDirection));
...@@ -1105,13 +1105,16 @@ class MysqliDb ...@@ -1105,13 +1105,16 @@ class MysqliDb
throw new Exception('Wrong order direction: ' . $orderbyDirection); throw new Exception('Wrong order direction: ' . $orderbyDirection);
} }
if (is_array($customFields)) { if (is_array($customFieldsOrRegExp)) {
foreach ($customFields as $key => $value) { foreach ($customFieldsOrRegExp as $key => $value) {
$customFields[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value); $customFieldsOrRegExp[$key] = preg_replace("/[^-a-z0-9\.\(\),_` ]+/i", '', $value);
} }
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFieldsOrRegExp) . '")';
$orderByField = 'FIELD (' . $orderByField . ', "' . implode('","', $customFields) . '")'; }elseif(is_string($customFieldsOrRegExp)){
} $orderByField = $orderByField . " REGEXP '" . $customFieldsOrRegExp . "'";
}elseif($customFieldsOrRegExp !== null){
throw new Exception('Wrong custom field or Regular Expression: ' . $customFieldsOrRegExp);
}
$this->_orderBy[$orderByField] = $orderbyDirection; $this->_orderBy[$orderByField] = $orderbyDirection;
return $this; return $this;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment