Skip to content

Commit

Permalink
[DomCrawler] Added ability to return empty string on `Crawler::text()…
Browse files Browse the repository at this point in the history
…` and `Crawler::html()` instead of an exception
  • Loading branch information
respinoza committed Sep 29, 2018
1 parent 3cd411a commit a6858eb
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/DomCrawler/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
`Image` classes is now optional.
* The `Crawler::children()` method will have a new `$selector` argument in version 5.0,
not defining it is deprecated.
* Added ability to return empty string on `Crawler::text()` and `Crawler::html()` instead of an exception

3.1.0
-----
Expand Down
14 changes: 14 additions & 0 deletions src/Symfony/Component/DomCrawler/Crawler.php
Original file line number Diff line number Diff line change
Expand Up @@ -570,13 +570,20 @@ public function nodeName()
/**
* Returns the node value of the first node of the list.
*
* @param bool $emptyString When set, it will return an empty string instead of an exception
*
* @return string The node value
*
* @throws \InvalidArgumentException When current node is empty
*/
public function text()
{
if (!$this->nodes) {
$args = func_get_args();
if (1 === \count($args) && true === $args[0]) {
return '';
}

throw new \InvalidArgumentException('The current node list is empty.');
}

Expand All @@ -586,13 +593,20 @@ public function text()
/**
* Returns the first node of the list as HTML.
*
* @param bool $emptyString When set, it will return an empty string instead of an exception
*
* @return string The node html
*
* @throws \InvalidArgumentException When current node is empty
*/
public function html()
{
if (!$this->nodes) {
$args = func_get_args();
if (1 === \count($args) && true === $args[0]) {
return '';
}

throw new \InvalidArgumentException('The current node list is empty.');
}

Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,8 @@ public function testText()
} catch (\InvalidArgumentException $e) {
$this->assertTrue(true, '->text() throws an \InvalidArgumentException if the node list is empty');
}

$this->assertSame('', $this->createTestCrawler(null)->filterXPath('//ol')->text(true));
}

public function testHtml()
Expand All @@ -405,6 +407,8 @@ public function testHtml()
} catch (\InvalidArgumentException $e) {
$this->assertTrue(true, '->html() throws an \InvalidArgumentException if the node list is empty');
}

$this->assertSame('', $this->createTestCrawler(null)->filterXPath('//ol')->html(true));
}

public function testExtract()
Expand Down

0 comments on commit a6858eb

Please sign in to comment.