Skip to content

Add DowngradeDomNodeChildNodesForeachRector for null $childNodes before PHP 8.0#379

Merged
TomasVotruba merged 1 commit into
mainfrom
downgrade-dom-childnodes-foreach
Jun 14, 2026
Merged

Add DowngradeDomNodeChildNodesForeachRector for null $childNodes before PHP 8.0#379
TomasVotruba merged 1 commit into
mainfrom
downgrade-dom-childnodes-foreach

Conversation

@TomasVotruba

Copy link
Copy Markdown
Member

Why

As of PHP 8.0, DOMNode::$childNodes always returns a DOMNodeList (php-src#5180, bug #79271). On PHP < 8.0 it returns null for nodes that cannot have children (e.g. DOMText, DOMDocumentType).

So code written for 8.0+ that iterates childNodes directly:

foreach ($node->childNodes as $childNode) { ... }

emits Warning: Invalid argument supplied for foreach() once downgraded and run on PHP 7.x. This was hit in real downgraded code (e.g. nunomaduro/termwind's Node::getChildNodes()).

What

New DowngradeDomNodeChildNodesForeachRector (PHP 8.0 set) that null-coalesces a foreach over DOMNode::$childNodes:

-foreach ($node->childNodes as $childNode) {
+foreach ($node->childNodes ?? [] as $childNode) {

It only fires when:

  • the iterated expression is a childNodes property fetch, and
  • the caller's type is DOMNode or a subtype (DOMElement, etc.).

Scoped to foreach on purpose: that is the documented warning and ?? [] is unambiguously safe there. Already-coalesced expressions, other properties (attributes), and non-DOM objects are skipped (covered by fixtures).

Registered in config/set/downgrade-php80.php. ECS, PHPStan and PHPUnit pass.

@TomasVotruba

Copy link
Copy Markdown
Member Author

Fixes bugs in tomasvotruba/lines using termwind that uses XML 👍

@TomasVotruba TomasVotruba merged commit 391a44d into main Jun 14, 2026
9 checks passed
@TomasVotruba TomasVotruba deleted the downgrade-dom-childnodes-foreach branch June 14, 2026 07:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant