Skip to content

Commit 0793daf

Browse files
committed
[DomCrawler] Add method flatText()
1 parent ed57e74 commit 0793daf

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

src/Symfony/Component/DomCrawler/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
3.4.0
5+
-----
6+
7+
* Added `flatText` method to get node value with spaces and newlines normalized.
8+
49
3.1.0
510
-----
611

src/Symfony/Component/DomCrawler/Crawler.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -571,6 +571,25 @@ public function text()
571571
return $this->getNode(0)->nodeValue;
572572
}
573573

574+
/**
575+
* Returns the flattened node value of the first node of the list.
576+
*
577+
* Surrounding spaces/newlines are removed,
578+
* and consecutive spaces/newlines are reduced to one space.
579+
*
580+
* @return string The flattened node value
581+
*
582+
* @throws \InvalidArgumentException When current node is empty
583+
*/
584+
public function flatText()
585+
{
586+
if (!$this->nodes) {
587+
throw new \InvalidArgumentException('The current node list is empty.');
588+
}
589+
590+
return trim(preg_replace('/\s+/', ' ', $this->getNode(0)->nodeValue));
591+
}
592+
574593
/**
575594
* Returns the first node of the list as HTML.
576595
*

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,18 @@ public function testText()
394394
}
395395
}
396396

397+
public function testFlatText()
398+
{
399+
$this->assertEquals('Fabien\'s Foo', $this->createTestCrawler()->filterXPath('//a[2]')->flatText(), '->flatText() returns the flattened node value of the first element of the node list');
400+
401+
try {
402+
$this->createTestCrawler()->filterXPath('//ol')->flatText();
403+
$this->fail('->flatText() throws an \InvalidArgumentException if the node list is empty');
404+
} catch (\InvalidArgumentException $e) {
405+
$this->assertTrue(true, '->flatText() throws an \InvalidArgumentException if the node list is empty');
406+
}
407+
}
408+
397409
public function testHtml()
398410
{
399411
$this->assertEquals('<img alt="Bar">', $this->createTestCrawler()->filterXPath('//a[5]')->html());

0 commit comments

Comments
 (0)