Skip to content

Commit

Permalink
Fix sort different array keys (#202)
Browse files Browse the repository at this point in the history
  • Loading branch information
PNixx authored Aug 9, 2023
1 parent 44942ae commit c76f0b8
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Liquid/StandardFilters.php
Original file line number Diff line number Diff line change
Expand Up @@ -559,11 +559,11 @@ public static function sort($input, $property = null)
$first = reset($input);
if ($first !== false && is_array($first) && array_key_exists($property, $first)) {
uasort($input, function ($a, $b) use ($property) {
if ($a[$property] == $b[$property]) {
if (($a[$property] ?? 0) == ($b[$property] ?? 0)) {
return 0;
}

return $a[$property] < $b[$property] ? -1 : 1;
return ($a[$property] ?? 0) < ($b[$property] ?? 0) ? -1 : 1;
});
}
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Liquid/StandardFiltersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,28 @@ public function testSort()
$this->assertEquals($expected, array_values(StandardFilters::sort(new \ArrayIterator($original), 'b')));
}

public function testSortWithoutKey()
{
// Sort by inner key
$original = array(
array('a' => 20, 'b' => 10),
array('a' => 45, 'b' => 5),
array('a' => 40, 'b' => 6),
array('a' => 30, 'b' => 48),
array('a' => 50),
);
$expected = array(
array('a' => 50),
array('a' => 45, 'b' => 5),
array('a' => 40, 'b' => 6),
array('a' => 20, 'b' => 10),
array('a' => 30, 'b' => 48),
);

$this->assertEquals($expected, array_values(StandardFilters::sort($original, 'b')));
$this->assertEquals($expected, array_values(StandardFilters::sort(new \ArrayIterator($original), 'b')));
}

/*
I've commented this out as its not one of the Ruby Standard Filters
Expand Down

0 comments on commit c76f0b8

Please sign in to comment.