-
-
Save wallacemaxters/ddeba5171e9fc49bc40bc82c1cd878e6 to your computer and use it in GitHub Desktop.
This file contains 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 | |
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(); | |
} | |
} | |
Author
wallacemaxters
commented
Jul 16, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment