2012-08-07 9 views
19

Khi tôi cố gắng đưa một số nội dung không tồn tại từ trang tôi bắt lỗi này:Làm thế nào tôi có thể kiểm tra an toàn là nút trống hay không? (Symfony 2 Crawler)

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

Làm thế nào tôi có thể an toàn kiểm tra tồn tại nội dung này hay không? Dưới đây một số ví dụ mà không hoạt động:

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 
} 

THANKS, tôi đã giúp bản thân mình với:

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

Cảm ơn người đàn ông. Giải pháp của bạn đã cứu tôi rất nhiều! –

+0

Số lượt kiểm tra đã giúp! –

Trả lời

5

Bạn đã thử một cái gì đó như thế này?

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

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

chức năng trống vẫn bị bỏ qua. –

+1

không hoạt động cho tôi. Nhưng sử dụng -> count() đã làm các trick – SuN

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