Skip to content

Commit

Permalink
Fix array where method with multiple input types
Browse files Browse the repository at this point in the history
  • Loading branch information
PNixx committed Dec 28, 2023
1 parent 36b1289 commit 47e5639
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/Liquid/StandardFilters.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,22 +166,25 @@ public static function json($input)
* Creates an array including only the objects with a given property value
* @link https://shopify.github.io/liquid/filters/where/
*
* @param array $input
* @param mixed $input
* @param string ...$args
*
* @return mixed
* @throws LiquidException
* @return array
*/
public static function where(array $input, string ...$args): array
public static function where($input, string ...$args)
{
switch (count($args)) {
case 1:
return array_filter($input, fn ($v) => ($v[$args[0]] ?? null) !== null);
case 2:
return array_filter($input, fn ($v) => ($v[$args[0]] ?? '') == $args[1]);
default:
throw new LiquidException('Wrong number of arguments to function `where`, given ' . count($args) . ', expected 1 or 2');
if (is_array($input)) {
switch (count($args)) {
case 1:
return array_values(array_filter($input, fn($v) => !in_array($v[$args[0]] ?? null, [null, false], true)));
case 2:
return array_values(array_filter($input, fn($v) => ($v[$args[0]] ?? '') == $args[1]));
default:
throw new LiquidException('Wrong number of arguments to function `where`, given ' . count($args) . ', expected 1 or 2');
}
}
return $input;
}

/**
Expand Down
9 changes: 9 additions & 0 deletions tests/Liquid/OutputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,15 @@ public function testFilterArrayTruthy()
$this->assertTemplateResult($expected, $text, ['cars' => [
['model' => 'bmw', 'available' => 1],
['model' => 'audi'],
['model' => 'toyota', 'available' => false],
]]);
}

public function testFilterArrayNull()
{
$text = ' {{ cars | where: "available" | json }} ';
$expected = ' null ';

$this->assertTemplateResult($expected, $text, []);
}
}

0 comments on commit 47e5639

Please sign in to comment.