Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes #166 #182

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/HTML5.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Masterminds;

use Masterminds\HTML5\Parser\DOMTreeBuilder;
use Masterminds\HTML5\Parser\Normalizer;
use Masterminds\HTML5\Parser\Scanner;
use Masterminds\HTML5\Parser\Tokenizer;
use Masterminds\HTML5\Serializer\OutputRules;
Expand All @@ -25,6 +26,9 @@ class HTML5

// Prevents the parser from automatically assigning the HTML5 namespace to the DOM document.
'disable_html_ns' => false,

// Whether to add missing root elements.
'normalize' => false,
);

protected $errors = array();
Expand Down Expand Up @@ -152,6 +156,10 @@ public function hasErrors()
*/
public function parse($input, array $options = array())
{
if (isset($options['normalize']) && $options['normalize']) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (! empty($options['normalize']) { would be more concise.

$input = $this->normalize($input);
}

$this->errors = array();
$options = array_merge($this->defaultOptions, $options);
$events = new DOMTreeBuilder(false, $options);
Expand Down Expand Up @@ -236,4 +244,18 @@ public function saveHTML($dom, $options = array())

return stream_get_contents($stream, -1, 0);
}

/**
* Add missing root elements to the input HTML.
*
* @param string $input
* @return string
*/
protected function normalize($input)
{
$normalizer = new Normalizer;
$normalizer->loadHtml($input);

return $normalizer->saveHtml();
}
}
203 changes: 203 additions & 0 deletions src/HTML5/Parser/Normalizer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
<?php

namespace Masterminds\HTML5\Parser;

/**
* Normalizes HTML.
*
* This class adds missing root elements, namely <html>, <head>, <body>. <!DOCTYPE> can optionally be added
* if specified in the tree structure - by default this is disabled.
*
* This library treats input HTML as a document fragment rather than a complete document (even if it has a DOCTYPE).
* DOMDocument automatically adds missing root elements so this class aims to replicate that functionality.
*
* @author Kieran Brahney <kieran@supportpal.com>
* @see https://github.com/Masterminds/html5-php/issues/166
*/
class Normalizer
{
/**
* Structure of a basic HTML document.
*
* @var array
*/
protected $tree = array(
'doctype' => '',
'html' => array(
'start' => '<html>',
'end' => '</html>',
'content' => array(),
),
'head' => array(
'start' => '<head>',
'end' => '</head>',
'content' => array(),
),
'body' => array(
'start' => '<body>',
'end' => '</body>',
'content' => array(),
),
);

/**
* What root element did we last add to.
*
* @var string|null
*/
protected $previousKey = null;

/**
* Parse a HTML document.
*
* @param string $html
* @return void
*/
public function loadHtml($html)
{
$i = 0;
$len = \strlen($html);
while ($i < $len) {
if ($html[$i] === '<') {
// Found a tag, get chars until the end of the tag.
$tag = '';
while ($i < $len && $html[$i] !== '>') {
$tag .= $html[$i++];
}

if ($i < $len && (string) $html[$i] === '>') {
$tag .= $html[$i++];

// Copy any whitespace following the tag.
// Anything added here needs to be added to the rtrim in the nodeName function.
while ($i < $len && \preg_match('/\s/', (string) $html[$i])) {
$tag .= $html[$i++];
}
} else {
// Missing closing tag?
$tag .= '>';
}

$this->addToTree($tag);
} else {
$this->addToTree($html[$i++]);
}
}
}

/**
* Format the document in a structured way (ensures root elements exists and moves scripts/css into <body>).
*
* @return string
*/
public function saveHtml()
{
// Initialise buffer.
$buffer = '';

// Add <!DOCTYPE> - this is optional.
$buffer .= $this->tree['doctype'];

// Add <html>
$buffer .= $this->tree['html']['start'];

// Add head
$buffer .= $this->tree['head']['start'];
foreach ($this->tree['head']['content'] as $node) {
$buffer .= $node;
}
$buffer .= $this->tree['head']['end'];

// Add body
$buffer .= $this->tree['body']['start'];
foreach ($this->tree['body']['content'] as $node) {
$buffer .= $node;
}
$buffer .= $this->tree['body']['end'];

// Close </html> tag
return $buffer . $this->tree['html']['end'];
}

/**
* Add a node into the tree for the correct parent.
*
* @param string $node
* @return void
*/
protected function addToTree($node)
{
if ($node[0] == '<') {
switch (\strtolower($this->nodeName($node))) {
case '!doctype':
if (empty($this->tree['doctype'])) {
$this->tree['doctype'] = $node;

return;
}

// Don't overwrite if we've already got a doctype definition.
return;

case 'html':
$this->addTo('html', $node, false);

return;

case 'head':
$this->addTo('head', $node, true);

return;

default:
$this->addTo(isset($this->previousKey) ? $this->previousKey : 'body', $node, true);

return;
}
}

// text node
$this->addTo(isset($this->previousKey) ? $this->previousKey : 'body', $node, true);
}

/**
* Add a node to the the tree.
*
* @param string $key
* @param string $node
* @param bool $setPrevious
* @return void
*/
protected function addTo($key, $node, $setPrevious)
{
$previousKey = $key;

if (\stripos($node, '<' . $key) !== false) {
$this->tree[$key]['start'] = $node;
} elseif (\stristr($node, '/' . $key . '>')) {
$this->tree[$key]['end'] = $node;
$previousKey = null;
} else {
$this->tree[$key]['content'][] = $node;
}

if ($setPrevious) {
$this->previousKey = $previousKey;
}
}

/**
* Get the name of a node without </>
*
* @param string $node
* @return string
*/
protected function nodeName($node)
{
$name = \preg_replace('/>\s*/', '', \ltrim($node, '</'));

$chunks = \explode(' ', $name);

return $chunks[0];
}
}
92 changes: 92 additions & 0 deletions test/HTML5/Parser/NormalizerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

namespace Masterminds\HTML5\Tests\Parser;

use Masterminds\HTML5\Parser\Normalizer;

class NormalizerTest extends \Masterminds\HTML5\Tests\TestCase
{
/**
* The aim of the HtmlNormalizer is to add missing root elements to HTML. It needs to be able
* to handle badly formatted HTML without throwing an error so this is what we're testing here.
*
* @return string[][]
*/
public function invalidHtmlDataProvider()
{
return array(
array(
'<head>',
'<html><head></head><body></body></html>'
),
array(
'</head>',
'<html><head></head><body></body></html>'
),
array(
'<head><meta charset="utf8" /></head>',
'<html><head><meta charset="utf8" /></head><body></body></html>'
),
array(
'<meta charset="utf8" /></head>',
'<html><head></head><body><meta charset="utf8" /></body></html>'
),
array(
'<meta charset="utf8" />',
'<html><head></head><body><meta charset="utf8" /></body></html>'
),
array(
'<body>',
'<html><head></head><body></body></html>'
),
array(
'<body>Hi</body>',
'<html><head></head><body>Hi</body></html>'
),
array(
'Hi</body>',
'<html><head></head><body>Hi</body></html>'
),
array(
'Hi',
'<html><head></head><body>Hi</body></html>'
),
array(
'<b',
'<html><head></head><body><b></body></html>'
),
array(
'<html>',
'<html><head></head><body></body></html>'
),
array(
'<html>Hi</html>',
'<html><head></head><body>Hi</body></html>'
),
array(
'Hi</html>',
'<html><head></head><body>Hi</body></html>'
),
array(
" <html>\n Hi</html> <body></body>",
"<html>\n <head></head><body> Hi</body></html> "
)
);
}

/**
* @test
*
* @param string $input
* @param string $expectedHtml
*
* @dataProvider invalidHtmlDataProvider
*/
public function renderRepairsBrokenHtml($input, $expectedHtml)
{
$parser = new Normalizer;
$parser->loadHtml($input);

$this->assertEquals($expectedHtml, $parser->saveHtml());
}
}