Skip to content

refactor: Replace gettype() checks with union type declarations #67

@usernane

Description

@usernane

Description

The codebase uses gettype() string comparisons for type branching — a PHP 5-era pattern. Since the library requires PHP 8.1+, these should be union type declarations on parameters, letting PHP enforce types at call time.

Examples

// Before
public function addChild($node, $attrsOrChain = [], bool $chainOnParent = false) {
    if (gettype($node) == 'string') {
        $toAdd = new HTMLNode($node);
    } else {
        $toAdd = $node;
    }
    $sType = gettype($attrsOrChain);
    if ($sType == 'boolean') { ... }
}

// After
public function addChild(HTMLNode|string $node, array|bool $attrsOrChain = [], bool $chainOnParent = false): HTMLNode {
    $toAdd = is_string($node) ? new HTMLNode($node) : $node;
    $chain = is_bool($attrsOrChain) ? $attrsOrChain : $chainOnParent;
}

Scope

Methods that need updating (non-exhaustive):

  • HTMLNode::addChild()$node, $attrsOrChain
  • HTMLNode::setAttribute()$val
  • HTMLNode::setAttributes()$attr key type check
  • HTMLNode::build()$child type check
  • HTMLNode::component()$loaded return check
  • HTMLNode::removeChild()$nodeInstOrId
  • HTMLList::addChild()$node
  • HeadNode::addChild()$node
  • TableRow::addChild()$node
  • TemplateCompiler::setComponentVars()$varsArr
  • TemplateCompiler::setSlotsHelper()$slotVal

Benefits

  • Static analysis tools (PHPStan/Psalm) can verify call sites
  • TypeError thrown immediately on invalid input instead of silent no-op
  • Clearer API contracts in IDE autocomplete
  • Removes ~40 gettype() calls

Backward Compatibility

Fully compatible for callers passing correct types. Callers passing null or wrong types that were silently ignored will now get TypeError — this surfaces existing bugs in caller code.

Acceptance Criteria

  • Zero gettype() calls remain in source code (replace with is_string(), is_array(), is_bool() where branching is still needed)
  • All public method parameters have declared types
  • All 308 tests pass unchanged

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions