From 46bd7a69b2828ffd2aba8c9aadbbb282c9ecac79 Mon Sep 17 00:00:00 2001 From: Jan Tojnar Date: Sat, 16 Mar 2024 21:33:29 +0100 Subject: [PATCH] Raise PHPStan version to 5 Converting `hasSingleTagInsideElement` into a type-safe getter will allow PHPStan to know the type of `newNode` is `DOMElement`. --- phpstan.neon | 2 +- src/Readability.php | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/phpstan.neon b/phpstan.neon index 252ad62..cb60e7e 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,5 +1,5 @@ parameters: - level: 4 + level: 5 paths: - src - tests diff --git a/src/Readability.php b/src/Readability.php index 82f09ae..6b53dc1 100644 --- a/src/Readability.php +++ b/src/Readability.php @@ -1035,8 +1035,8 @@ protected function grabArticle(?JSLikeHTMLElement $page = null): ?JSLikeHTMLElem } } - if ($this->hasSingleTagInsideElement($node, 'p') && $this->getLinkDensity($node) < 0.25) { - $newNode = $node->childNodes->item(0); + $newNode = $this->getSingleTagInsideElement($node, 'p'); + if (null !== $newNode && $this->getLinkDensity($node) < 0.25) { $node->parentNode->replaceChild($newNode, $node); $nodesToScore[] = $newNode; } @@ -1538,10 +1538,10 @@ private function isPhrasingContent($node): bool /** * Checks if `$node` has only whitespace and a single element with `$tag` for the tag name. - * Returns false if `$node` contains non-empty text nodes + * Returns the matched element, or `null` if `$node` contains non-empty text nodes * or if it contains no element with given tag or more than 1 element. */ - private function hasSingleTagInsideElement(JSLikeHTMLElement $node, string $tag): bool + private function getSingleTagInsideElement(JSLikeHTMLElement $node, string $tag): ?JSLikeHTMLElement { $childNodes = iterator_to_array($node->childNodes); $children = array_filter($childNodes, fn ($childNode) => $childNode instanceof \DOMElement); @@ -1554,7 +1554,7 @@ private function hasSingleTagInsideElement(JSLikeHTMLElement $node, string $tag) // And there should be no text nodes with real content $a = array_filter($childNodes, fn ($childNode) => $childNode instanceof \DOMText && preg_match($this->regexps['hasContent'], $this->getInnerText($childNode))); - return 0 === \count($a); + return 0 === \count($a) ? $children[0] : null; } /**