Fix empty array check

This commit is contained in:
Daniel J. Summers 2024-07-04 13:16:04 -04:00
parent 5201e564ca
commit 1a37b009ea
2 changed files with 21 additions and 6 deletions

View File

@ -34,15 +34,17 @@ class Parameters
$name => method_exists($document, 'toJson') ? $document->toJson($flags) : json_encode($document, $flags) $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); $key = array_key_first($document);
if (is_array($document[$key]) && method_exists($document[$key][array_key_first($document[$key])], 'toJson')) { 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 [ return [
$name => sprintf('{%s:[%s]}', json_encode($key, $flags), $name => sprintf('{%s:[%s]}', json_encode($key, $flags),
implode(',', array_map(fn($it) => $it->toJson($flags), $document[$key]))) implode(',', array_map(fn($it) => $it->toJson($flags), $document[$key])))
]; ];
} }
}
return [$name => json_encode($document, $flags)]; return [$name => json_encode($document, $flags)];
} }

View File

@ -33,6 +33,19 @@ class ParametersTest extends TestCase
'JSON parameter not constructed correctly'); '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')] #[TestDox('json succeeds for stdClass')]
public function testJsonSucceedsForStdClass(): void public function testJsonSucceedsForStdClass(): void
{ {