8000 [DomCrawler] Added argument `$default` to method `Crawler::attr()` · symfony/symfony@942a302 · GitHub
[go: up one dir, main page]

Skip to content

Commit 942a302

Browse files
Rastishkanicolas-grekas
authored andcommitted
[DomCrawler] Added argument $default to method Crawler::attr()
1 parent ff654da commit 942a302

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

src/Symfony/Component/DomCrawler/CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ CHANGELOG
66

77
* Add `CrawlerAnySelectorTextContains` test constraint
88
* Add `CrawlerAnySelectorTextSame` test constraint
9+
* Added argument `$default` to `Crawler::attr()`
910

1011
6.3
1112
---

src/Symfony/Component/DomCrawler/Crawler.php

+9-3
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ class Crawler implements \Countable, \IteratorAggregate
5858
*/
5959
private bool $isHtml = true;
6060

61-
6261
private ?HTML5 $html5Parser = null;
6362

6463
/**
@@ -522,17 +521,24 @@ public function children(string $selector = null): static
522521
/**
523522
* Returns the attribute value of the first node of the list.
524523
*
524+
* @param string|null $default When not null: the value to return when the node or attribute is empty
525+
*
525526
* @throws \InvalidArgumentException When current node is empty
526527
*/
527-
public function attr(string $attribute): ?string
528+
public function attr(string $attribute/* , string $default = null */): ?string
528529
{
530+
$default = \func_num_args() > 1 ? func_get_arg(1) : null;
529531
if (!$this->nodes) {
532+
if (null !== $default) {
533+
return $default;
534+
}
535+
530536
throw new \InvalidArgumentException('The current node list is empty.');
531537
}
532538

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

535-
return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
541+
return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : $default;
536542
}
537543

538544
/**

src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTestCase.php

+3
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,9 @@ public function testAttr()
305305
} catch (\InvalidArgumentException $e) {
306306
$this->assertTrue(true, '->attr() throws an \InvalidArgumentException if the node list is empty');
307307
}
308+
309+
$this->assertSame('my value', $this->createTestCrawler()->filterXPath('//notexists')->attr('class', 'my value'));
310+
$this->assertSame('my value', $this->createTestCrawler()->filterXPath('//li')->attr('attr-not-exists', 'my value'));
308311
}
309312

310313
public function testMissingAttrValueIsNull()

0 commit comments

Comments
 (0)
0