Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Last active July 17, 2018 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wallacemaxters/ddeba5171e9fc49bc40bc82c1cd878e6 to your computer and use it in GitHub Desktop.
Save wallacemaxters/ddeba5171e9fc49bc40bc82c1cd878e6 to your computer and use it in GitHub Desktop.
<?php
class Parser
{
protected $template;
const SPECIAL_ATTRIBUTE_PREFIX = 'php-';
public function __construct($template)
{
$this->template = $template;
$dom = new DomDocument('1.0');
$dom->loadHtml($this->template);
$this->domDocument = $dom;
}
public function getDomDocument()
{
return $this->domDocument;
}
protected function processAttributes(DOMNamedNodeMap $attrs, DomElement $node)
{
foreach($attrs as $attr) {
if (strpos($attr->name, static::SPECIAL_ATTRIBUTE_PREFIX) !== 0) continue;
// Processa as paradas do PHP aqui!
$name = substr($attr->name, strlen(static::SPECIAL_ATTRIBUTE_PREFIX));
$method = 'parseAttribute' . ucfirst($name);
if (! method_exists($this, $method)) {
throw new \RuntimeException("Method '{$name}' not yet implemented");
}
$node->removeAttribute($attr->name);
$this->$method($node, $attr);
}
}
protected function recursiveNodeProcess(DomElement $nodes)
{
foreach ($nodes->childNodes as $node) {
$node->hasChildNodes() && $this->recursiveNodeProcess($node);
if ($node->nodeType === XML_ELEMENT_NODE){
$this->processAttributes($node->attributes, $node);
}
}
}
protected function parseAttributeBind(DomElement $node, DomAttr $attr)
{
$node->removeAttribute(static::SPECIAL_ATTRIBUTE_PREFIX . 'bind');
$node->nodeValue = ''; // remove all childs!
$expression = sprintf('<?= %s; ?>', $this->normalizePHPExpression($attr->value));
$php = $this->getDomDocument()->createCDATASection($expression);
$node->appendChild($php);
}
protected function parseAttributeForeach(DomElement $node, DomAttr $attr)
{
$dom = $this->getDomDocument();
$expressionStart = sprintf('<?php foreach(%s): ?>', $this->normalizePHPExpression($attr->value));
$expressionEnd = '<?php endforeach ?>';
$node->insertBefore($dom->createCDATASection($expressionStart), $node->firstChild);
$node->appendChild($dom->createCDATASection($expressionEnd));
}
protected function normalizePHPExpression($string)
{
return rtrim($string, ';');
}
public function parse()
{
$dom = $this->getDomDocument();
$this->recursiveNodeProcess(
$dom->documentElement
);
//$dom->formatOutput = true;
return $dom->saveHtml();
}
}
@wallacemaxters
Copy link
Author

error_reporting(-1);
ini_set('display_errors', 'On');

$parser = new Parser(
	"<!doctype html5><html>
		<body>
			<div php-foreach='\$array as \$i'>
				<div item='1' php-bind='\$i + 1'>Olá</div>
			</div>
		</body>
	</html>"
);



echo $parser->parse();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment