spatie/phpunit-snapshot-assertions

add HTML driver

Closed this issue · 1 comments

Hey,

I thought it's possible to use the XmlDriver for HTML but this only works as long as the HTML isn't a whole page which starts with <!DOCTYPE html>. In this case it will throw an exception.

ErrorException: DOMDocument::loadXML(): Opening and ending tag mismatch: link line 12 and head in Entity, line: 14

So I would say that adding a new HtmlDriver would be useful?

namespace Spatie\Snapshots\Drivers;

use DOMDocument;
use PHPUnit\Framework\Assert;
use Spatie\Snapshots\Driver;
use Spatie\Snapshots\Exceptions\CantBeSerialized;

class HtmlDriver implements Driver
{
    public function serialize($data): string
    {
        if (! is_string($data)) {
            throw new CantBeSerialized('Only strings can be serialized to html');
        }

        $domDocument = new DOMDocument('1.0');
        $domDocument->preserveWhiteSpace = false;
        $domDocument->formatOutput = true;

        @$domDocument->loadHTML($data);

        return $domDocument->saveHTML();
    }

    public function extension(): string
    {
        return 'html';
    }

    public function match($expected, $actual)
    {
        Assert::assertEquals($expected, $this->serialize($actual));
    }
}

Feel free to take a stab at it! 👍