Navigation Menu

Skip to content

Commit

Permalink
Fixes attr method returning empty string for missing attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Obuhovich authored and fabpot committed Nov 23, 2013
1 parent d8893c4 commit 13168bc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Symfony/Component/DomCrawler/Crawler.php
Expand Up @@ -484,7 +484,9 @@ public function attr($attribute)
throw new \InvalidArgumentException('The current node list is empty.');
}

return $this->getNode(0)->getAttribute($attribute);
$node = $this->getNode(0);

return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
Expand Up @@ -321,6 +321,17 @@ public function testAttr()
}
}

public function testMissingAttrValueIsNull()
{
$crawler = new Crawler();
$crawler->addContent('<html><div non-empty-attr="sample value" empty-attr=""></div></html>', 'text/html; charset=UTF-8');
$div = $crawler->filterXPath('//div');

$this->assertEquals('sample value', $div->attr('non-empty-attr'), '->attr() reads non-empty attributes correctly');
$this->assertEquals('', $div->attr('empty-attr'), '->attr() reads empty attributes correctly');
$this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly');
}

public function testText()
{
$this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list');
Expand Down

0 comments on commit 13168bc

Please sign in to comment.