Skip to content

Commit

Permalink
[DomCrawler] Added argument $default to method Crawler::attr()
Browse files Browse the repository at this point in the history
  • Loading branch information
Rastishka authored and nicolas-grekas committed Aug 16, 2023
1 parent 2463efd commit 3137148
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ CHANGELOG
6.4
---

* Add `CrawlerAnySelectorTextContains` test constraint
* Add `CrawlerAnySelectorTextSame` test constraint
* Add `CrawlerAnySelectorTextContains` test constraint
* Add `CrawlerAnySelectorTextSame` test constraint
* Add argument `$default` to `Crawler::attr()`

6.3
---
Expand Down
12 changes: 9 additions & 3 deletions Crawler.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ class Crawler implements \Countable, \IteratorAggregate
*/
private bool $isHtml = true;


private ?HTML5 $html5Parser = null;

/**
Expand Down Expand Up @@ -522,17 +521,24 @@ public function children(string $selector = null): static
/**
* Returns the attribute value of the first node of the list.
*
* @param string|null $default When not null: the value to return when the node or attribute is empty
*
* @throws \InvalidArgumentException When current node is empty
*/
public function attr(string $attribute): ?string
public function attr(string $attribute/* , string $default = null */): ?string
{
$default = \func_num_args() > 1 ? func_get_arg(1) : null;
if (!$this->nodes) {
if (null !== $default) {
return $default;
}

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

$node = $this->getNode(0);

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

/**
Expand Down
3 changes: 3 additions & 0 deletions Tests/AbstractCrawlerTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,9 @@ public function testAttr()
} catch (\InvalidArgumentException $e) {
$this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty');
}

$this->assertSame('my value', $this->createTestCrawler()->filterXPath('//notexists')->attr('class', 'my value'));
$this->assertSame('my value', $this->createTestCrawler()->filterXPath('//li')->attr('attr-not-exists', 'my value'));
}

public function testMissingAttrValueIsNull()
Expand Down

0 comments on commit 3137148

Please sign in to comment.