From 1a37b009ea0fd5d5af5fee6b73c8f839484b4001 Mon Sep 17 00:00:00 2001 From: "Daniel J. Summers" Date: Thu, 4 Jul 2024 13:16:04 -0400 Subject: [PATCH] Fix empty array check --- src/Parameters.php | 14 ++++++++------ tests/unit/ParametersTest.php | 13 +++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Parameters.php b/src/Parameters.php index 5cae1c1..63f351c 100644 --- a/src/Parameters.php +++ b/src/Parameters.php @@ -34,14 +34,16 @@ class Parameters $name => method_exists($document, 'toJson') ? $document->toJson($flags) : json_encode($document, $flags) ]; } - if (empty($document)) return [$name => json_encode($document, $flags)]; $key = array_key_first($document); - if (is_array($document[$key]) && method_exists($document[$key][array_key_first($document[$key])], 'toJson')) { - return [ - $name => sprintf('{%s:[%s]}', json_encode($key, $flags), - implode(',', array_map(fn($it) => $it->toJson($flags), $document[$key]))) - ]; + if (is_array($document[$key])) { + if (empty($document[$key])) return [$name => json_encode($document, $flags)]; + if (method_exists($document[$key][array_key_first($document[$key])], 'toJson')) { + return [ + $name => sprintf('{%s:[%s]}', json_encode($key, $flags), + implode(',', array_map(fn($it) => $it->toJson($flags), $document[$key]))) + ]; + } } return [$name => json_encode($document, $flags)]; } diff --git a/tests/unit/ParametersTest.php b/tests/unit/ParametersTest.php index 97685da..8efed4f 100644 --- a/tests/unit/ParametersTest.php +++ b/tests/unit/ParametersTest.php @@ -33,6 +33,19 @@ class ParametersTest extends TestCase 'JSON parameter not constructed correctly'); } + public function testJsonSucceedsForArrayWithEmptyArrayParameter(): void + { + $this->assertEquals([':it' => '{"id":18,"urls":[]}'], Parameters::json(':it', ['id' => 18, 'urls' => []]), + 'JSON parameter not constructed correctly'); + } + + #[TestDox('json succeeds for 1D array with empty array parameter')] + public function testJsonSucceedsFor1DArrayWithEmptyArrayParameter(): void + { + $this->assertEquals([':it' => '{"urls":[]}'], Parameters::json(':it', ['urls' => []]), + 'JSON parameter not constructed correctly'); + } + #[TestDox('json succeeds for stdClass')] public function testJsonSucceedsForStdClass(): void {