Last active
February 8, 2018 17:58
-
-
Save whymarrh/5864443 to your computer and use it in GitHub Desktop.
Assert HTML validity with PHPUnit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use PHPUnit_Framework_Exception; | |
use PHPUnit_Framework_TestCase; | |
use SimpleXMLElement; | |
class BaseTestCase extends PHPUnit_Framework_TestCase | |
{ | |
/** | |
* Show as much error information as possible | |
*/ | |
protected $traceError = TRUE; | |
/** | |
* Assert that the given HTML validates | |
* | |
* Modified <http://git.io/BNxJcA>. Read the terms of service for | |
* Validator.nu at <http://about.validator.nu/#tos>. | |
* | |
* @param string $html The HTML to validate | |
*/ | |
public function assertValidHtml($html) | |
{ | |
// cURL | |
$curl = curl_init(); | |
curl_setopt_array($curl, [ | |
CURLOPT_URL => 'http://html5.validator.nu/', | |
CURLOPT_RETURNTRANSFER => TRUE, | |
CURLOPT_POST => TRUE, | |
CURLOPT_POSTFIELDS => [ | |
'out' => 'xml', | |
'content' => $html, | |
], | |
]); | |
$response = curl_exec($curl); | |
if (!$response) { | |
$this->markTestIncomplete('Issues checking HTML validity.'); | |
} | |
curl_close($curl); | |
// Fail if errors | |
$xml = new SimpleXMLElement($response); | |
$nonDocumentErrors = $xml->{'non-document-error'}; | |
$errors = $xml->error; | |
if (count($nonDocumentErrors) > 0) { | |
// Indeterminate | |
$this->markTestIncomplete(); | |
} elseif (count($errors) > 0) { | |
// Invalid | |
$this->fail("HTML output did not validate."); | |
} | |
// Valid | |
$this->assertTrue(TRUE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment