Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[DomCrawler] hasChildren() function #8048

Closed
@ghost

Description

It's currently not possible to know if an element has children without getting notices when the input is an empty div:

$elem->children()->count();

(even when just doing $elem->children())

Notice: Trying to get property of non-object in /Users/wesley/Sites/xyz/goutte.phar/vendor/symfony/dom-crawler/Symfony/Component/DomCrawler/Crawler.php on line 738

Notice: Trying to get property of non-object in /Users/wesley/Sites/xyz/goutte.phar/vendor/symfony/dom-crawler/Symfony/Component/DomCrawler/Crawler.php on line 741

This is due to the call to the sibling function with:

$this->getNode(0)->firstChild

An empty div has no firstChild so in the sibling function this generates the notice above.

One could fix this by adding a function such as:

public function hasChildren()
{
    if (!count($this) || !$this->getNode(0)->firstChild || (new static($this->sibling($this->getNode(0)->firstChild), $this->uri))->count() == 0) {
        return false;
    } else {
        return true;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions