How to check for a class present on an element with Symfony DOMcrawler?

535 Views Asked by At

I have a $foo which is an instance of Crawler and $foo->outerHtml() starts with <div class="brick brick--type--test brick--id--1. I am writing a test and I'd like to assert brick--id--1 is indeed present as a class. How could I do this? (preg_match() on $foo->outerHtml() invokes Cthulhu, I'd rather not)

2

There are 2 best solutions below

2
Oluwafemi Sule On BEST ANSWER

Evaluate an XPATH expression against the nodes to check whether they contain the CSS class.

<?php

require('vendor/autoload.php');
use Symfony\Component\DomCrawler\Crawler;

$html = <<<'HTML'
<!DOCTYPE html>
<html>
    <body>
        <div class="brick brick--type--test brick--id--1">Hello</div>
    </body>
</html>
HTML;

$crawler = new Crawler($html);

$foo = $crawler->filter('body > div');
$class = 'brick--id--1';
$expr = "contains(concat(' ',normalize-space(@class),' '),' $class ')";
$result = $foo->evaluate($expr);
var_dump($result);
// array(1) {
//   [0]=>
//   bool(true)
// }
var_dump(array_sum($result) !== 0);
// bool(true)
2
Michael Strelan On
$crawler->matches('.brick--id--1');