Skip to content

Commit

Permalink
fix: allow content to be empty when calling Crawler::html() method (#616
Browse files Browse the repository at this point in the history
)

* 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
  • Loading branch information
syl20b authored Feb 28, 2024
1 parent ef9a6f2 commit 732d630
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/DomCrawler/Crawler.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

Expand Down
20 changes: 19 additions & 1 deletion tests/DomCrawler/CrawlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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
*/
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/basic.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ <h1>Main</h1>
<p class="p-2">P2</p>
<input name="in" value="test">
<p class="price" data-old-price="42">36</p>
<div class="empty"></div>
</body>
</html>

0 comments on commit 732d630

Please sign in to comment.