From 4767694ce7559ed1018e0af3992b2063ba051f1b Mon Sep 17 00:00:00 2001 From: Bilge Date: Sun, 1 Aug 2021 11:01:14 +0100 Subject: [PATCH] [DomCrawler] Added Crawler::innerText() method --- src/Symfony/Component/DomCrawler/CHANGELOG.md | 5 +++++ src/Symfony/Component/DomCrawler/Crawler.php | 8 ++++++++ .../DomCrawler/Tests/AbstractCrawlerTest.php | 16 ++++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/src/Symfony/Component/DomCrawler/CHANGELOG.md b/src/Symfony/Component/DomCrawler/CHANGELOG.md index 3262b4a562d3d..6904b37aacdf1 100644 --- a/src/Symfony/Component/DomCrawler/CHANGELOG.md +++ b/src/Symfony/Component/DomCrawler/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +5.4 +--- + + * Add `Crawler::innerText` method. + 5.3 --- diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 7a668686eec01..f0dd8511b4a6b 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -634,6 +634,14 @@ public function text(string $default = null, bool $normalizeWhitespace = true) return $text; } + /** + * Returns only the inner text that is the direct descendent of the current node, excluding any child nodes. + */ + public function innerText(): string + { + return $this->filterXPath('.//text()')->text(); + } + /** * Returns the first node of the list as HTML. * diff --git a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php index 77183348e9932..aafe47dfe0bbd 100644 --- a/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/AbstractCrawlerTest.php @@ -354,6 +354,18 @@ public function testText() $this->assertSame('my value', $this->createTestCrawler(null)->filterXPath('//ol')->text('my value')); } + /** + * Tests that innerText() returns only text that is the direct descendent of the current node, in contrast to + * text() that returns the text of all child nodes. + */ + public function testInnerText() + { + self::assertCount(1, $crawler = $this->createTestCrawler()->filterXPath('//*[@id="complex-element"]')); + + self::assertSame('Parent text Child text', $crawler->text()); + self::assertSame('Parent text', $crawler->innerText()); + } + public function testHtml() { $this->assertEquals('Bar', $this->createTestCrawler()->filterXPath('//a[5]')->html()); @@ -1283,6 +1295,10 @@ public function createTestCrawler($uri = null)
+
+ Parent text + Child text +
');