Fix "Undefined array key 0" error

If a matching element isn't the first child (e.g. preceded by a whitespace
text node), it may sit at a key other than 0 after some cleanup, leading to
a "Undefined array key 0" error.

This fix is now covered by 6 tests.

Fixes #96

Signed-off-by: Kevin Decherf <kevin@kdecherf.com>
This commit is contained in:
Kevin Decherf
2026-06-21 17:06:38 +02:00
parent 18bfe842f8
commit 7db754debe
2 changed files with 51 additions and 1 deletions
+8 -1
View File
@@ -1483,8 +1483,15 @@ class Readability implements LoggerAwareInterface
$childNodes = iterator_to_array($node->childNodes);
$children = array_filter($childNodes, static fn ($childNode) => $childNode instanceof \DOMElement);
// array_first() has been added in PHP 8.5, failing back for older versions
if (!\function_exists('array_first')) {
$firstChild = $children ? $children[array_key_first($children)] : null;
} else {
$firstChild = array_first($children);
}
// There should be exactly 1 element child with given tag
if (1 !== \count($children) || $children[0]->nodeName !== $tag) {
if (1 !== \count($children) || $firstChild->nodeName !== $tag) {
return false;
}