Skip to content

Commit 732d630

Browse files
authored
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
1 parent ef9a6f2 commit 732d630

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

src/DomCrawler/Crawler.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -229,13 +229,13 @@ public function html(string $default = null): string
229229
return $this->webDriver->getPageSource();
230230
}
231231

232-
return $this->attr('outerHTML');
232+
return $this->attr('outerHTML', (string) $default);
233233
} catch (\InvalidArgumentException $e) {
234234
if (null === $default) {
235235
throw $e;
236236
}
237237

238-
return (string) $default;
238+
return $default;
239239
}
240240
}
241241

tests/DomCrawler/CrawlerTest.php

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ public function testChildren(callable $clientFactory): void
242242
$names[$i] = $c->nodeName();
243243
});
244244

245-
$this->assertSame(['h1', 'main', 'p', 'p', 'input', 'p'], $names);
245+
$this->assertSame(['h1', 'main', 'p', 'p', 'input', 'p', 'div'], $names);
246246
}
247247

248248
/**
@@ -385,6 +385,24 @@ public function testHtmlDefault(callable $clientFactory): void
385385
$this->assertSame('default', $crawler->filter('header')->html('default'));
386386
}
387387

388+
/**
389+
* @dataProvider clientFactoryProvider
390+
*/
391+
public function testEmptyHtml(callable $clientFactory): void
392+
{
393+
$crawler = $this->request($clientFactory, '/basic.html');
394+
$this->assertEmpty($crawler->filter('.empty')->html(''));
395+
}
396+
397+
/**
398+
* @dataProvider clientFactoryProvider
399+
*/
400+
public function testEmptyHtmlWithoutDefault(callable $clientFactory): void
401+
{
402+
$crawler = $this->request($clientFactory, '/basic.html');
403+
$this->assertEmpty($crawler->filter('.empty')->html());
404+
}
405+
388406
/**
389407
* @dataProvider clientFactoryProvider
390408
*/

tests/fixtures/basic.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,6 @@ <h1>Main</h1>
1616
<p class="p-2">P2</p>
1717
<input name="in" value="test">
1818
<p class="price" data-old-price="42">36</p>
19+
<div class="empty"></div>
1920
</body>
2021
</html>

0 commit comments

Comments
 (0)