| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Models\Query; |
| 4 |
|
| 5 |
use FluentCart\Framework\Database\Orm\Builder; |
| 6 |
use FluentCart\Framework\Support\Arr; |
| 7 |
|
| 8 |
class Sort |
| 9 |
{ |
| 10 |
static function make(): Sort |
| 11 |
{ |
| 12 |
return new static(); |
| 13 |
} |
| 14 |
|
| 15 |
|
| 16 |
public function apply(Builder $query, array $sortCriteria) |
| 17 |
{ |
| 18 |
if (empty($sortCriteria)) { |
| 19 |
return; |
| 20 |
} |
| 21 |
|
| 22 |
foreach ($sortCriteria as $key => $criteria) { |
| 23 |
$key = Arr::get($criteria, 'key'); |
| 24 |
if (empty($key)) { |
| 25 |
continue; |
| 26 |
} |
| 27 |
// Validate column name to prevent SQL injection — only allow alphanumeric, underscores, and dots (for table.column) |
| 28 |
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_.]*$/', $key)) { |
| 29 |
continue; |
| 30 |
} |
| 31 |
$order = Arr::get($criteria, 'order') === 'descending' ? 'desc' : 'asc'; |
| 32 |
$query->orderBy($key, $order); |
| 33 |
} |
| 34 |
} |
| 35 |
} |