From 9d1f62c6ddc801b81f3ac72e4a201c288295ac57 Mon Sep 17 00:00:00 2001 From: Benjamin Nussbaum Date: Wed, 27 Aug 2025 21:31:21 +0200 Subject: [PATCH] feat: add Liquid filters 'parse_json' --- app/Liquid/Filters/Data.php | 11 ++++++ tests/Unit/Liquid/Filters/DataTest.php | 48 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/app/Liquid/Filters/Data.php b/app/Liquid/Filters/Data.php index bbf613b..2bbb5a9 100644 --- a/app/Liquid/Filters/Data.php +++ b/app/Liquid/Filters/Data.php @@ -78,4 +78,15 @@ class Data extends FiltersProvider return $array[array_rand($array)]; } + + /** + * Parse a JSON string into a PHP value + * + * @param string $json The JSON string to parse + * @return mixed The parsed JSON value + */ + public function parse_json(string $json): mixed + { + return json_decode($json, true); + } } diff --git a/tests/Unit/Liquid/Filters/DataTest.php b/tests/Unit/Liquid/Filters/DataTest.php index 5937670..1e56b91 100644 --- a/tests/Unit/Liquid/Filters/DataTest.php +++ b/tests/Unit/Liquid/Filters/DataTest.php @@ -277,3 +277,51 @@ test('sample filter works with mixed data types', function () { $result = $filter->sample($array); expect($result)->toBeIn($array); }); + +test('parse_json filter parses JSON string to array', function () { + $filter = new Data(); + $jsonString = '[{"a":1,"b":"c"},"d"]'; + + $result = $filter->parse_json($jsonString); + expect($result)->toBe([['a' => 1, 'b' => 'c'], 'd']); +}); + +test('parse_json filter parses simple JSON object', function () { + $filter = new Data(); + $jsonString = '{"name":"John","age":30,"city":"New York"}'; + + $result = $filter->parse_json($jsonString); + expect($result)->toBe(['name' => 'John', 'age' => 30, 'city' => 'New York']); +}); + +test('parse_json filter parses JSON array', function () { + $filter = new Data(); + $jsonString = '["apple","banana","cherry"]'; + + $result = $filter->parse_json($jsonString); + expect($result)->toBe(['apple', 'banana', 'cherry']); +}); + +test('parse_json filter parses nested JSON structure', function () { + $filter = new Data(); + $jsonString = '{"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}],"total":2}'; + + $result = $filter->parse_json($jsonString); + expect($result)->toBe([ + 'users' => [ + ['id' => 1, 'name' => 'Alice'], + ['id' => 2, 'name' => 'Bob'] + ], + 'total' => 2 + ]); +}); + +test('parse_json filter handles primitive values', function () { + $filter = new Data(); + + expect($filter->parse_json('"hello"'))->toBe('hello'); + expect($filter->parse_json('123'))->toBe(123); + expect($filter->parse_json('true'))->toBe(true); + expect($filter->parse_json('false'))->toBe(false); + expect($filter->parse_json('null'))->toBe(null); +});