From 732d630efbf18bfa554ee593671819f56f43780d Mon Sep 17 00:00:00 2001 From: syl20b Date: Wed, 28 Feb 2024 14:47:44 +0100 Subject: [PATCH] fix: allow content to be empty when calling Crawler::html() method (#616) * fix: allow content to be empty when calling Crawler::html() method * use default value when content is empty * cast default value as string * add test when no default value is provided --- src/DomCrawler/Crawler.php | 4 ++-- tests/DomCrawler/CrawlerTest.php | 20 +++++++++++++++++++- tests/fixtures/basic.html | 1 + 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/DomCrawler/Crawler.php b/src/DomCrawler/Crawler.php index 5798d50d..a78ddd7e 100644 --- a/src/DomCrawler/Crawler.php +++ b/src/DomCrawler/Crawler.php @@ -229,13 +229,13 @@ public function html(string $default = null): string return $this->webDriver->getPageSource(); } - return $this->attr('outerHTML'); + return $this->attr('outerHTML', (string) $default); } catch (\InvalidArgumentException $e) { if (null === $default) { throw $e; } - return (string) $default; + return $default; } } diff --git a/tests/DomCrawler/CrawlerTest.php b/tests/DomCrawler/CrawlerTest.php index 03d7855f..dc6f5b8c 100644 --- a/tests/DomCrawler/CrawlerTest.php +++ b/tests/DomCrawler/CrawlerTest.php @@ -242,7 +242,7 @@ public function testChildren(callable $clientFactory): void $names[$i] = $c->nodeName(); }); - $this->assertSame(['h1', 'main', 'p', 'p', 'input', 'p'], $names); + $this->assertSame(['h1', 'main', 'p', 'p', 'input', 'p', 'div'], $names); } /** @@ -385,6 +385,24 @@ public function testHtmlDefault(callable $clientFactory): void $this->assertSame('default', $crawler->filter('header')->html('default')); } + /** + * @dataProvider clientFactoryProvider + */ + public function testEmptyHtml(callable $clientFactory): void + { + $crawler = $this->request($clientFactory, '/basic.html'); + $this->assertEmpty($crawler->filter('.empty')->html('')); + } + + /** + * @dataProvider clientFactoryProvider + */ + public function testEmptyHtmlWithoutDefault(callable $clientFactory): void + { + $crawler = $this->request($clientFactory, '/basic.html'); + $this->assertEmpty($crawler->filter('.empty')->html()); + } + /** * @dataProvider clientFactoryProvider */ diff --git a/tests/fixtures/basic.html b/tests/fixtures/basic.html index b3c1f6f4..0fd9a248 100644 --- a/tests/fixtures/basic.html +++ b/tests/fixtures/basic.html @@ -16,5 +16,6 @@

Main

P2

36

+