Skip to content

Support proper return value of DOMDocument::createElement, false almost never happens #13792

@janedbal

Description

@janedbal

Feature request

Currently, PHPStan infers benevolent union to prevent usability degradation while using this function. But this makes us unable to use checkBenevolentUnionTypes: true.

Luckily, the false can be statically eliminated by checking the argument passed (any valid name never returns false nor throw exception). I believe that most of the time, constant strings are used there.

Examples that Return FALSE:

$doc = new DOMDocument();
$doc->strictErrorChecking = false;  // Critical: must be disabled

// All of these return FALSE:
$doc->createElement('123element');    // Starts with digit
$doc->createElement('my element');    // Contains space
$doc->createElement('my@element');    // Contains @ symbol
$doc->createElement('');              // Empty name
$doc->createElement('!element');      // Starts with !
$doc->createElement('elem&ent');      // Contains ampersand
$doc->createElement('.element');      // Starts with dot
$doc->createElement('-element');      // Starts with hyphen

Behavior Modes:

strictErrorChecking Invalid Name Behavior Valid Name Behavior
true (default) Throws DOMException Returns DOMElement
false Returns FALSE + Warning Returns DOMElement

See real behaviour as proof. I also let Claude Code analyse php-src to verify this behaviour.

Did PHPStan help you today? Did it make you happy in any way?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions