From 85cb5d48d6f066ea4ec41f8355ae290e324b64f8 Mon Sep 17 00:00:00 2001 From: Nelson Castillo Date: Thu, 2 Apr 2026 16:16:37 +0000 Subject: [PATCH] Fix undefined array key 0 in RW::parseError() when results is empty parseError() crashes when the API returns a successful response with an empty results array. The else branch tries to access results[0] even though the key check just confirmed it doesn't exist. Added a count check so we skip the block entirely when there's nothing to parse. Fixes #98 --- src/AbraFlexi/RW.php | 2 +- .../AbraFlexi/ParseErrorEmptyResultsTest.php | 62 +++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 tests/src/AbraFlexi/ParseErrorEmptyResultsTest.php diff --git a/src/AbraFlexi/RW.php b/src/AbraFlexi/RW.php index b6650ff..72b94d7 100644 --- a/src/AbraFlexi/RW.php +++ b/src/AbraFlexi/RW.php @@ -166,7 +166,7 @@ public function parseError(array $responseDecoded) $this->errors = $responseDecoded['errors']; } - if (\array_key_exists('results', $responseDecoded) && \is_array($responseDecoded['results'])) { + if (\array_key_exists('results', $responseDecoded) && \is_array($responseDecoded['results']) && \count($responseDecoded['results']) > 0) { if (\array_key_exists(0, $responseDecoded['results'])) { foreach ($responseDecoded['results'] as $result) { if (\array_key_exists('request-id', $result)) { diff --git a/tests/src/AbraFlexi/ParseErrorEmptyResultsTest.php b/tests/src/AbraFlexi/ParseErrorEmptyResultsTest.php new file mode 100644 index 0000000..390ca76 --- /dev/null +++ b/tests/src/AbraFlexi/ParseErrorEmptyResultsTest.php @@ -0,0 +1,62 @@ + true]); + + // Simulate the API response that causes the crash: + // success is true but results is an empty array + $responseDecoded = [ + 'success' => 'true', + 'stats' => [ + 'created' => '0', + 'updated' => '0', + 'deleted' => '0', + 'skipped' => '0', + 'failed' => '0', + ], + 'results' => [], + ]; + + // This should not throw "Undefined array key 0" + $errorCount = $rw->parseError($responseDecoded); + + $this->assertSame(0, $errorCount); + } + + /** + * @covers \AbraFlexi\RW::parseError + */ + public function testParseErrorWithNonEmptyResultsStillWorks(): void + { + $rw = new RW(null, ['offline' => true]); + + $responseDecoded = [ + 'results' => [ + [ + 'errors' => [ + ['message' => 'Some error', 'for' => 'field'], + ], + ], + ], + ]; + + $errorCount = $rw->parseError($responseDecoded); + + $this->assertGreaterThan(0, $errorCount); + } +}