Skip to content

Commit 331f186

Browse files
committed
add HTML driver
1 parent 38d1b73 commit 331f186

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
],
2222
"require": {
2323
"php": "^7.2",
24+
"ext-dom": "*",
2425
"phpunit/phpunit": "^8.0",
2526
"symfony/yaml": "^4.0"
2627
},

src/Drivers/HtmlDriver.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
namespace Spatie\Snapshots\Drivers;
4+
5+
use DOMDocument;
6+
use PHPUnit\Framework\Assert;
7+
use Spatie\Snapshots\Driver;
8+
use Spatie\Snapshots\Exceptions\CantBeSerialized;
9+
10+
class HtmlDriver implements Driver
11+
{
12+
public function serialize($data): string
13+
{
14+
if (! is_string($data)) {
15+
throw new CantBeSerialized('Only strings can be serialized to html');
16+
}
17+
18+
$domDocument = new DOMDocument('1.0');
19+
$domDocument->preserveWhiteSpace = false;
20+
$domDocument->formatOutput = true;
21+
22+
@$domDocument->loadHTML($data); // to ignore HTML5 errors
23+
24+
return $domDocument->saveHTML();
25+
}
26+
27+
public function extension(): string
28+
{
29+
return 'html';
30+
}
31+
32+
public function match($expected, $actual)
33+
{
34+
Assert::assertEquals($expected, $this->serialize($actual));
35+
}
36+
}

src/MatchesSnapshots.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use PHPUnit\Framework\ExpectationFailedException;
66
use ReflectionClass;
77
use ReflectionObject;
8+
use Spatie\Snapshots\Drivers\HtmlDriver;
89
use Spatie\Snapshots\Drivers\JsonDriver;
910
use Spatie\Snapshots\Drivers\VarDriver;
1011
use Spatie\Snapshots\Drivers\XmlDriver;
@@ -55,6 +56,11 @@ public function assertMatchesSnapshot($actual, Driver $driver = null)
5556
$this->doSnapshotAssertion($actual, $driver ?? new VarDriver());
5657
}
5758

59+
public function assertMatchesHtmlSnapshot($actual)
60+
{
61+
$this->assertMatchesSnapshot($actual, new HtmlDriver());
62+
}
63+
5864
public function assertMatchesXmlSnapshot($actual)
5965
{
6066
$this->assertMatchesSnapshot($actual, new XmlDriver());

0 commit comments

Comments
 (0)