Grégoire Pineau
Contributed by Grégoire Pineau in #33144

The DomCrawler component is mostly used in Symfony applications via functional tests, to filter the DOM nodes of HTML/XML documents. The methods provided by DomCrawler were originally inspired by jQuery, such as eq(), first(), children(), nextAll(), etc.

In Symfony 4.4 we've added three new methods frequently requested by the community: matches(), closest() and outerHtml(). Consider the following HTML snippet:

1
2
3
4
5
6
7
8
9
10
11
12
13
<html lang="en">
<body>
    <div class="class-1">
        <h1 class="class-1">Lorem Ipsum</h1>

        <ul class="class-2 class-3" id="id-1">
            <li>1</li>
            <li class="class-4">2</li>
            <li>3</li>
        </ul>
    </div>
</body>
</html>

The matches(string $selector) method returns true if the node matches the given CSS selector:

1
2
$crawler->filter('#id-1')->matches('.class-3');  // true
$crawler->filter('#id-1')->matches('.class-4');  // false

The closest(string $selector) method returns the first ancestor of the node that matches the given CSS selector:

1
2
3
// returns the div.class-1 node and NOT the h1.class-1 node because h1 is
// a sibling and not an ancestor of ul#id-1
$crawler->filter('#id-1')->closest('.class-1');

The outerHtml() method returns the whole HTML content of the node, including its own tags:

1
2
3
4
5
// returns '<ul class="class-2 class-3" id="id-1"><li>1</li><li class="class-4">2</li><li>3</li></ul>'
$crawler->filter('#id-1')->outerHtml();

// returns '<li>1</li><li class="class-4">2</li><li>3</li>'
$crawler->filter('#id-1')->html();

Removing all Extra White Space

Hamza Amrouche
Contributed by Hamza Amrouche in #32440

Dealing with white spaces is pretty annoying when checking the contents of some HTML tag. For example, with the following HTML snippet:

1
2
3
4
5
<div class="class-1">
    <h2>
        Some Title Text
    </h2>
</div>

The following test will fail because of all the "n" and spaces that surround the title text:

1
2
// this fails because of the extra white spaces
$this->assertSame('Some Title Text', $crawler->filter('.class-1')->text());

In Symfony 4.3 we introduced the assertSelectorTextContains() method to help in these situations, but starting from Symfony 4.4, you can also pass true as the second optional argument of text() to remove all extra white spaces:

1
2
// this passes because all extra white spaces are removed
$this->assertSame('Some Title Text', $crawler->filter('.class-1')->text(null, true));

In addition to trimming white spaces from the beginning and the end of the string, this feature also replaces two or more white spaces inside the contents by a single white space. For example, if the original text is foo bar baz, it returns foo bar baz.

Published in #Living on the edge