From 792d986049a2cd13319c215c9560fe5a75fcf30a Mon Sep 17 00:00:00 2001 From: nixx Date: Thu, 28 Dec 2023 09:44:00 +0300 Subject: [PATCH] Fix array where method with multiple input types --- src/Liquid/StandardFilters.php | 23 +++++++++++++---------- tests/Liquid/OutputTest.php | 9 +++++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/Liquid/StandardFilters.php b/src/Liquid/StandardFilters.php index d3a8bf6..25b876f 100644 --- a/src/Liquid/StandardFilters.php +++ b/src/Liquid/StandardFilters.php @@ -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 * * @throws LiquidException - * @return array + * @return mixed */ - 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; } /** diff --git a/tests/Liquid/OutputTest.php b/tests/Liquid/OutputTest.php index 1b2fdf5..c9e300b 100644 --- a/tests/Liquid/OutputTest.php +++ b/tests/Liquid/OutputTest.php @@ -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, []); + } }