我怎样才能安全地检查为节点为空或不? (2 Symfony的履带)(How can I safe

2019-07-30 20:29发布

当我尝试采取从页面不存在的一些内容我抓住这个错误:

The current node list is empty.
500 Internal Server Error - InvalidArgumentException 

我怎样才能安全地检查存在该内容,否则不? 这里是一些例子不工作:

if($crawler->filter('.PropertyBody')->eq(2)->text()){
    // bla bla
}

if(!empty($crawler->filter('.PropertyBody')->eq(2)->text())){
    // bla bla
}
if(($crawler->filter('.PropertyBody')->eq(2)->text()) != null){
    // bla bla
}

谢谢,我顺手拿有:

$count = $crawler->filter('.PropertyBody')->count();
if($count > 2){
    $marks = $crawler->filter('.PropertyBody')->eq(2)->text();
}

Answer 1:

您是否尝试过这样的事情?

$text = null;
if (!empty($body = $crawler->filter('.PropertyBody'))) {
    if (!empty($node = $body->eq(2))) {
        $text = $node->text();
    }
}

$this->assertContains('yourText', $text);


Answer 2:

$marks = $crawler->filter('.PropertyBody')->count()
    ? $crawler->filter('.PropertyBody')->eq(2)->text() 
    : '';


Answer 3:

try {
    $text = $crawler->filter('.PropertyBody')->eq(2)->text();
} catch (\InvalidArgumentException $e) {
    // Handle the current node list is empty..
}


文章来源: How can I safely check is node empty or not? (Symfony 2 Crawler)