Skip to content
This repository was archived by the owner on Aug 22, 2023. It is now read-only.

Commit fdba54f

Browse files
committed
PHPORM-46 Throw an exception when Query\Builder::orderBy() is used with invalid direction
1 parent 843904b commit fdba54f

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

src/Query/Builder.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,11 +513,20 @@ public function distinct($column = false)
513513

514514
/**
515515
* @inheritdoc
516+
* @param int|string $direction
516517
*/
517518
public function orderBy($column, $direction = 'asc')
518519
{
519520
if (is_string($direction)) {
520-
$direction = (strtolower($direction) == 'asc' ? 1 : -1);
521+
$direction = match (strtolower($direction)) {
522+
'asc' => 1,
523+
'desc' => -1,
524+
default => throw new \InvalidArgumentException(sprintf('Order direction must be either "asc" or "desc", "%s" given.', $direction)),
525+
};
526+
}
527+
528+
if ($direction !== 1 && $direction !== -1) {
529+
throw new \InvalidArgumentException(sprintf('Order direction must be either 1 or -1, "%s" given.', $direction));
521530
}
522531

523532
if ($column == 'natural') {

tests/QueryBuilderTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -863,4 +863,17 @@ public function testCursor()
863863
$this->assertEquals($data[$i]['name'], $result['name']);
864864
}
865865
}
866+
867+
/**
868+
* @testWith ["dasc"]
869+
* [0]
870+
* [10]
871+
* [true]
872+
*/
873+
public function testOrderByInvalidDirection($direction)
874+
{
875+
$this->expectException(\InvalidArgumentException::class);
876+
$this->expectExceptionMessage('Order direction must be either ');
877+
DB::collection('items')->orderBy('_id', $direction)->get();
878+
}
866879
}

0 commit comments

Comments
 (0)