Skip to content

Support single-file component inputs #29

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

Merged
merged 7 commits into from
Jun 5, 2025
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
vendor
node_modules/
composer.lock
.phpunit.result.cache
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
],
"license": "LGPL-2.1-only",
"require": {
"ext-dom": "*",
"ext-libxml": "*",
"php": ">=7.2"
},
"autoload": {
Expand Down
82 changes: 13 additions & 69 deletions src/Component.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,104 +4,47 @@

use DOMAttr;
use DOMCharacterData;
use DOMDocument;
use DOMElement;
use DOMNode;
use DOMNodeList;
use DOMText;
use Exception;
use LibXMLError;

use WMDE\VueJsTemplating\JsParsing\BasicJsExpressionParser;
use WMDE\VueJsTemplating\JsParsing\CachingExpressionParser;
use WMDE\VueJsTemplating\JsParsing\JsExpressionParser;

class Component {

/**
* @var string HTML
* @var DOMElement
*/
private $template;
private $rootNode;

/**
* @var JsExpressionParser
*/
private $expressionParser;

/**
* @param string $template HTML
* @param DOMElement $rootNode
* @param callable[] $methods
*/
public function __construct( $template, array $methods ) {
$this->template = $template;
public function __construct( DOMElement $rootNode, array $methods ) {
$this->rootNode = $rootNode;
$this->expressionParser = new CachingExpressionParser( new BasicJsExpressionParser( $methods ) );
}

/**
* Note: this method is not currently safe to call repeatedly
* (the internal root node is modified in-place).
*
* @param array $data
*
* @return string HTML
*/
public function render( array $data ) {
$document = $this->parseHtml( $this->template );

$rootNode = $this->getRootNode( $document );
$this->handleNode( $rootNode, $data );

return $document->saveHTML( $rootNode );
}

/**
* @param string $html HTML
*
* @return DOMDocument
*/
private function parseHtml( $html ) {
if ( LIBXML_VERSION < 20900 ) {
$entityLoaderDisabled = libxml_disable_entity_loader( true );
}
$internalErrors = libxml_use_internal_errors( true );
$document = new DOMDocument( '1.0', 'UTF-8' );

// Ensure $html is treated as UTF-8, see https://stackoverflow.com/a/8218649
// LIBXML_NOBLANKS Constant excludes "ghost nodes" to avoid violating
// vue's single root node constraint
if ( !$document->loadHTML( '<?xml encoding="utf-8" ?>' . $html, LIBXML_NOBLANKS ) ) {
//TODO Test failure
}

/** @var LibXMLError[] $errors */
$errors = libxml_get_errors();
libxml_clear_errors();

// Restore previous state
libxml_use_internal_errors( $internalErrors );
if ( LIBXML_VERSION < 20900 ) {
libxml_disable_entity_loader( $entityLoaderDisabled );
}

foreach ( $errors as $error ) {
//TODO html5 tags can fail parsing
//TODO Throw an exception
}

return $document;
}

/**
* @param DOMDocument $document
*
* @return DOMElement
* @throws Exception
*/
private function getRootNode( DOMDocument $document ) {
$rootNodes = $document->documentElement->childNodes->item( 0 )->childNodes;

if ( $rootNodes->length > 1 ) {
throw new Exception( 'Template should have only one root node' );
}
$this->handleNode( $this->rootNode, $data );

return $rootNodes->item( 0 );
return $this->rootNode->ownerDocument->saveHTML( $this->rootNode );
}

/**
Expand Down Expand Up @@ -245,8 +188,9 @@ private function handleFor( DOMNode $node, array $data ) {
}

private function appendHTML( DOMNode $parent, $source ) {
$tmpDoc = $this->parseHtml( $source );
foreach ( $tmpDoc->getElementsByTagName( 'body' )->item( 0 )->childNodes as $node ) {
$htmlParser = new HtmlParser();
$tmpDoc = $htmlParser->parseHtml( $source );
foreach ( $htmlParser->getBodyElement( $tmpDoc )->childNodes as $node ) {
$node = $parent->ownerDocument->importNode( $node, true );
$parent->appendChild( $node );
}
Expand Down
175 changes: 175 additions & 0 deletions src/HtmlParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
<?php

declare( strict_types = 1 );

namespace WMDE\VueJsTemplating;

use DOMDocument;
use DOMElement;
use Exception;
use LibXMLError;

/**
* Methods for parsing HTML strings and extracting elements from them.
*/
class HtmlParser {

/**
* Parse the given HTML string into a DOM document.
*/
public function parseHtml( string $html ): DOMDocument {
if ( LIBXML_VERSION < 20900 ) {
$entityLoaderDisabled = libxml_disable_entity_loader( true );
}
$internalErrors = libxml_use_internal_errors( true );
$document = new DOMDocument( '1.0', 'UTF-8' );

// Ensure $html is treated as UTF-8, see https://stackoverflow.com/a/8218649
// LIBXML_NOBLANKS Constant excludes "ghost nodes" to avoid violating
// vue's single root node constraint
if ( !$document->loadHTML( '<?xml encoding="utf-8" ?>' . $html, LIBXML_NOBLANKS ) ) {
//TODO Test failure
}

/** @var LibXMLError[] $errors */
$errors = libxml_get_errors();
libxml_clear_errors();

// Restore previous state
libxml_use_internal_errors( $internalErrors );
if ( LIBXML_VERSION < 20900 ) {
libxml_disable_entity_loader( $entityLoaderDisabled );
}

foreach ( $errors as $error ) {
//TODO html5 tags can fail parsing
//TODO Throw an exception
}

return $document;
}

/**
* Get the root node of the template represented by the given document.
*/
public function getRootNode( DOMDocument $document ): DOMElement {
$htmlElement = $this->getHtmlElement( $document );
$headOrBody = $this->getSoleHeadOrBody( $htmlElement );
$rootNodeParent = $this->getTemplateElement( $headOrBody ) ?? $headOrBody;
$rootNode = $this->getOnlySubstantialChild( $rootNodeParent );
return $rootNode;
}

/**
* Get the `<html>` element of the given document.
*/
public function getHtmlElement( DOMDocument $document ): DOMElement {
$documentElement = $document->documentElement;
if ( $documentElement === null ) {
throw new Exception( 'Empty document' );
}
if ( $documentElement->tagName !== 'html' ) {
throw new Exception( "Expected <html>, got <{$documentElement->tagName}>" );
}
return $documentElement;
}

/**
* Get the `<body>` element of the given document.
*/
public function getBodyElement( DOMDocument $document ): DOMElement {
$htmlElement = $this->getHtmlElement( $document );
$bodyElement = $htmlElement->childNodes[0];
if ( $bodyElement->tagName !== 'body' ) {
throw new Exception( "Expected <body>, got <{$bodyElement->tagName}>" );
}
return $bodyElement;
}

/**
* Get the `<head>` or `<body>` element of the given document,
* asserting that it is the only child (cannot have both nor any other children).
*/
private function getSoleHeadOrBody( DOMElement $htmlElement ): DOMElement {
$length = $htmlElement->childNodes->length;
if ( $length !== 1 ) {
throw new Exception( "Expected exactly 1 <html> child, got $length" );
}

$child = $htmlElement->childNodes[0];
$tagName = $child->tagName;
if ( $tagName !== 'head' && $tagName !== 'body' ) {
throw new Exception( "Expected <head> or <body>, got <$tagName>" );
}

return $child;
}

/**
* Get the `<template>` element of the given `<head>` or `<body>` element,
* discarding any adjacent `<script>` or `<style>` elements
* if the input is in Single-File Component (SFC) syntax.
*/
private function getTemplateElement( DOMElement $rootElement ): ?DOMElement {
$onlyTemplateElement = null;
foreach ( $rootElement->childNodes as $node ) {
if ( $node->nodeType === XML_COMMENT_NODE ) {
// comment node, ignore
continue;
} elseif ( $node->nodeType === XML_TEXT_NODE ) {
if ( trim( $node->textContent ) === '' ) {
// whitespace-only text node, ignore
continue;
} else {
// not SFC
$onlyTemplateElement = null;
break;
}
}
if ( $node->tagName === 'template' ) {
if ( $onlyTemplateElement === null ) {
$onlyTemplateElement = $node;
} else {
// more than one <template>, handle as non-SFC and throw error below
$onlyTemplateElement = null;
break;
}
} elseif ( $node->tagName !== 'script' && $node->tagName !== 'style' ) {
// top-level tag other than <template>, <script> or <style> => not SFC
$onlyTemplateElement = null;
break;
}
}
return $onlyTemplateElement;
}

/**
* Get the only “substantial” child of the given element.
* Ignore any adjacent comments or whitespace-only text nodes
* (such as line breaks or indentation).
*/
private function getOnlySubstantialChild( DOMElement $element ): DOMElement {
$onlySubstantialChild = null;
foreach ( $element->childNodes as $node ) {
if ( $node->nodeType === XML_COMMENT_NODE ) {
// comment node, ignore
continue;
} elseif ( $node->nodeType === XML_TEXT_NODE && trim( $node->textContent ) === '' ) {
// whitespace-only text node, ignore
continue;
}
if ( $onlySubstantialChild === null ) {
$onlySubstantialChild = $node;
} else {
throw new Exception( 'Template should only have one root node' );
}
}

if ( $onlySubstantialChild !== null ) {
return $onlySubstantialChild;
} else {
throw new Exception( 'Template contained no root node' );
}
}

}
5 changes: 4 additions & 1 deletion src/Templating.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ class Templating {
* @return string
*/
public function render( $template, array $data, array $methods = [] ) {
$component = new Component( $template, $methods );
$htmlParser = new HtmlParser();
$document = $htmlParser->parseHtml( $template );
$rootNode = $htmlParser->getRootNode( $document );
$component = new Component( $rootNode, $methods );
return $component->render( $data );
}

Expand Down
66 changes: 66 additions & 0 deletions tests/php/HtmlParserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace WMDE\VueJsTemplating\Test;

use DOMElement;
use Exception;
use PHPUnit\Framework\TestCase;
use WMDE\VueJsTemplating\HtmlParser;

/**
* @covers \WMDE\VueJsTemplating\HtmlParser
*/
class HtmlParserTest extends TestCase {

private function parseAndGetRootNode( string $html ): DOMElement {
$htmlParser = new HtmlParser();
$document = $htmlParser->parseHtml( $html );
return $htmlParser->getRootNode( $document );
}

private function assertIsDivTest( DOMElement $element ): void {
$this->assertSame( 'div', $element->tagName );
$this->assertSame( 'test', $element->getAttribute( 'class' ) );
}

public function testSingleRootNode(): void {
$rootNode = $this->parseAndGetRootNode( '<div class="test"></div>' );
$this->assertIsDivTest( $rootNode );
}

public function testSingleFileComponent_OnlyTemplate(): void {
$rootNode = $this->parseAndGetRootNode( '<template><div class="test"></div></template>' );
$this->assertIsDivTest( $rootNode );
}

public function testSingleFileComponent_TemplateAndScriptAndStyle(): void {
$template = '<template><div class="test"></div></template><script></script><style></style>';
$rootNode = $this->parseAndGetRootNode( $template );
$this->assertIsDivTest( $rootNode );
}

public function testSingleFileComponent_ScriptAndTemplateAndStyle(): void {
$template = '<script></script><template><div class="test"></div></template><style></style>';
$rootNode = $this->parseAndGetRootNode( $template );
$this->assertIsDivTest( $rootNode );
}

public function testEmptyDocument(): void {
$this->expectException( Exception::class );
$this->expectExceptionMessage( 'Empty document' );
$this->parseAndGetRootNode( '' );
}

public function testHeadElement(): void {
$html = '<html><head><title>Title</title></head><body>ABC</body></html>';
$this->expectException( Exception::class );
$this->expectExceptionMessage( 'Expected exactly 1 <html> child, got 2' );
$this->parseAndGetRootNode( $html );
}

public function testTwoRootNodes() {
$this->expectException( Exception::class );
$this->parseAndGetRootNode( '<p></p><p></p>' );
}

}
Loading