diff --git a/src/Filters/Custom/TernaryFilter.php b/src/Filters/Custom/TernaryFilter.php new file mode 100644 index 0000000..45854c4 --- /dev/null +++ b/src/Filters/Custom/TernaryFilter.php @@ -0,0 +1,19 @@ +toLiquidValue() : $input; + + return match (true) { + $inputValue === null, $inputValue === '', $inputValue === [], $inputValue === false => $falseValue, + default => $trueValue, + }; + } +} diff --git a/tests/Integration/CustomFiltersTest.php b/tests/Integration/CustomFiltersTest.php new file mode 100644 index 0000000..0fa0012 --- /dev/null +++ b/tests/Integration/CustomFiltersTest.php @@ -0,0 +1,19 @@ +factory = \Keepsuit\Liquid\EnvironmentFactory::new() + ->setStrictVariables(true) + ->registerFilters(\Keepsuit\Liquid\Filters\Custom\TernaryFilter::class); +}); + +test('ternary', function () { + expect(renderTemplate('{{ true | ternary: "yes", "no" }}', factory: $this->factory))->toBe('yes'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => ['a']]))->toBe('yes'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => 'a']))->toBe('yes'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => new \Keepsuit\Liquid\Tests\Stubs\IntegerDrop('1')]))->toBe('yes'); + + expect(renderTemplate('{{ false | ternary: "yes", "no" }}', factory: $this->factory))->toBe('no'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => []]))->toBe('no'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => '']))->toBe('no'); + expect(renderTemplate('{{ test | ternary: "yes", "no" }}', factory: $this->factory, assigns: ['test' => null]))->toBe('no'); +});