View source
<?php
require_once 'tree/HamlNode.php';
require_once 'HamlHelpers.php';
require_once 'HamlException.php';
class HamlParser {
const DEBUG_NONE = 0;
const DEBUG_SHOW_SOURCE = 1;
const DEBUG_SHOW_OUTPUT = 2;
const DEBUG_SHOW_ALL = 3;
const REGEX_HAML = '/(?m)^([ \\x09]*)((?::(\\w*))?(?:%([\\w:-]*))?(?:\\.((?:(?:[-_:a-zA-Z]|#\\{.+?\\})+(?:[-:\\w]|#\\{.+?\\})*(?:\\.?))*))?(?:#((?:[_:a-zA-Z]|#\\{.+?\\})+(?:[-:\\w]|#\\{.+?\\})*))?(?:\\[(.+)\\])?(?:(\\()((?:(?:\\w+\\(.*?\\)|data[\\t ]*=[\\t ]*\\{.+?\\}|(?:[_:a-zA-Z]+[-:\\w]*)[\\t ]*=[\\t ]*.+)[\\t ]*)+\\)))?(?:(\\{)((?:(?:\\w+\\(.*?\\)|:data[\\t ]*=>[\\t ]*\\{.+?\\}|:(?:[_:a-zA-Z]+[-:\\w]*)[\\t ]*=>?[\\t ]*.+)(?:,?[\\t ]*)?)+\\}))?(\\|?>?\\|?<?) *((?:\\?#)|!!!|\\/\\/|\\/|-#|!=|&=|!|&|=|-|~|\\\\\\\\)? *(.*?)(?:\\s(\\|)?)?)$/';
const REGEX_ATTRIBUTES = '/:?(?:(data)\\s*=>?\\s*([({].*?[})]))|(\\w+(?:[-:]\\w*)*)\\s*=>?\\s*(?(?=\\[)(?:\\[(.+?)\\])|(?(?=([\'"]))(?:[\'"](.*?)\\5)|([^\\s,]+)))/';
const REGEX_ATTRIBUTE_FUNCTION = '/^\\$?[_a-zA-Z]\\w*(?(?=->)(->[_a-zA-Z]\\w*)+|(::[_a-zA-Z]\\w*)?)\\(.+\\)$/';
const REGEX_WHITESPACE_REMOVAL = '/(.*?)\\s+$/s';
const REGEX_WHITESPACE_REMOVAL_DEBUG = '%(.*?)(?:<br />\\s)$%s';
const MATCH_INTERPOLATION = '/(?<!\\\\)#\\{(.*?)\\}/';
const INTERPOLATE = '<?php echo \\1; ?>';
const HTML_ATTRS = '/html_attrs\\(\\s*((?(?=\')(?:.*?)\'|(?:.*?)"))(?:\\s*,\\s*(.*?))?\\)/';
const HAML_HAML = 0;
const HAML_INDENT = 1;
const HAML_SOURCE = 2;
const HAML_FILTER = 3;
const HAML_TAG = 4;
const HAML_CLASS = 5;
const HAML_ID = 6;
const HAML_OBJECT_REFERENCE = 7;
const HAML_OPEN_XML_ATTRIBUTES = 8;
const HAML_XML_ATTRIBUTES = 9;
const HAML_OPEN_RUBY_ATTRIBUTES = 10;
const HAML_RUBY_ATTRIBUTES = 11;
const HAML_WHITESPACE_REMOVAL = 12;
const HAML_TOKEN = 13;
const HAML_CONTENT = 14;
const HAML_MULTILINE = 15;
const DOCTYPE = '!!!';
const HAML_COMMENT = '!(-#|//)!';
const XML_COMMENT = '/';
const SELF_CLOSE_TAG = '/';
const ESCAPE_XML = '&=';
const UNESCAPE_XML = '!=';
const INSERT_CODE = '=';
const INSERT_CODE_PRESERVE_WHITESPACE = '~';
const RUN_CODE = '-';
const INNER_WHITESPACE_REMOVAL = '<';
const OUTER_WHITESPACE_REMOVAL = '>';
const BLOCK_LEFT_OUTER_WHITESPACE_REMOVAL = '|>';
const BLOCK_RIGHT_OUTER_WHITESPACE_REMOVAL = '>|';
const MULTILINE = ' |';
const OPEN_XML_ATTRIBUTES = '(';
const CLOSE_XML_ATTRIBUTES = ')';
const OPEN_RUBY_ATTRIBUTES = '{';
const CLOSE_RUBY_ATTRIBUTES = '}';
const DIRECTIVE = '?#';
const SOURCE_DEBUG = 's';
const OUTPUT_DEBUG = 'o';
const IS_XML_PROLOG = 'XML';
const XML_PROLOG = "<?php echo \"<?xml version='1.0' encoding='{encoding}' ?>\n\"; ?>";
const DEFAULT_XML_ENCODING = 'utf-8';
const XML_ENCODING = '{encoding}';
private $format = 'xhtml';
private $doctype;
private $escapeHtml = false;
private $suppressEval = false;
private $attrWrapper = '"';
private $styles = array(
'nested',
'expanded',
'compact',
'compressed',
);
private $style = 'nested';
private $ugly = true;
private $preserveComments = false;
private $debug = self::DEBUG_NONE;
private $filterDir;
private $helperFile;
private $helperClass = 'HamlHelpers';
private $doctypes = array(
'html4' => array(
'<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'Strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD 4.01 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'Frameset' => '<!DOCTYPE html PUBLIC "-//W3C//DTD 4.01 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
),
'html5' => array(
'<!DOCTYPE html>',
),
'xhtml' => array(
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'Strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'Frameset' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'5' => '<!DOCTYPE html>',
'1.1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'Basic' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'Mobile' => '<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">',
'RDFa' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
),
);
private $emptyTags = array(
'meta',
'img',
'link',
'br',
'hr',
'input',
'area',
'param',
'col',
'base',
);
private $inlineTags = array(
'a',
'abbr',
'accronym',
'b',
'big',
'cite',
'code',
'dfn',
'em',
'i',
'kbd',
'q',
'samp',
'small',
'span',
'strike',
'strong',
'tt',
'u',
'var',
);
private $minimizedAttributes = array(
'compact',
'checked',
'declare',
'readonly',
'disabled',
'selected',
'defer',
'ismap',
'nohref',
'noshade',
'nowrap',
'multiple',
'noresize',
);
private $preserve = array(
'pre',
'textarea',
);
private $indentChar;
private $indentChars = array(
' ',
"\t",
);
private $indentSpaces;
private $filters = array();
private $inFilter = false;
private $showOutput;
private $showSource;
private $line;
private $filename;
private $source;
public function __construct($options = array()) {
if (isset($options['language'])) {
Phamlp::$language = $options['language'];
unset($options['language']);
}
foreach ($options as $name => $value) {
$this->{$name} = $value;
}
if ($this->ugly) {
$this->style = 'compressed';
}
$this->format = strtolower($this->format);
if (is_null($this->doctype) && !array_key_exists($this->format, $this->doctypes)) {
throw new HamlException('Invalid {what} ({value}). Must be one of "{options}"', array(
'{what}' => 'format',
'{value}' => $this->format,
'{options}' => join(', ', array_keys($this->doctypes)),
), $this);
}
$this->showSource = $this->debug & HamlParser::DEBUG_SHOW_SOURCE;
$this->showOutput = $this->debug & HamlParser::DEBUG_SHOW_OUTPUT;
require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'HamlHelpers.php';
if (isset($this->helperFile)) {
require_once $this->helperFile;
$this->helperClass = basename($this->helperFile, ".php");
if (!is_subclass_of($this->helperClass, 'HamlHelpers')) {
throw new HamlException('{what} must extend {base} class', array(
'{what}' => $this->helperClass,
'{base}' => 'HamlHelpers',
), $this);
}
}
}
public function __get($name) {
$getter = 'get' . ucfirst($name);
if (method_exists($this, $getter)) {
return $this
->{$getter}();
}
throw new HamlException('No getter function for {what}', array(
'{what}' => $name,
));
}
public function getFilename() {
return $this->filename;
}
public function getLine() {
return $this->line;
}
public function getSource() {
return $this->source;
}
public function parse($sourceFile, $cacheDir = null, $permission = 0755, $sourceExtension = '.haml', $outputExtension = '.php') {
if (is_string($cacheDir) || is_bool($cacheDir)) {
if (is_bool($cacheDir)) {
$cacheDir = $cacheDir ? dirname(__FILE__) . DIRECTORY_SEPARATOR . 'haml-cache' : dirname($sourceFile);
}
$outputFile = $cacheDir . DIRECTORY_SEPARATOR . basename($sourceFile, $sourceExtension) . $outputExtension;
if (!is_file($outputFile) || @filemtime($sourceFile) > @filemtime($outputFile)) {
if (!is_dir($cacheDir)) {
@mkdir($cacheDir, $permission);
}
$return = file_put_contents($outputFile, $this
->haml2PHP($sourceFile)) === false ? false : $outputFile;
if ($return !== false) {
@chmod($outputFile, $permission);
}
}
else {
$return = $outputFile;
}
}
else {
$return = $this
->haml2PHP($sourceFile);
}
return $return;
}
public function haml2PHP($sourceFile) {
$this->line = 0;
$this->filename = $sourceFile;
$helpers = "<?php\nrequire_once '" . dirname(__FILE__) . DIRECTORY_SEPARATOR . "HamlHelpers.php';\n";
if (isset($this->helperFile)) {
$helpers .= "require_once '{$this->helperFile}';\n";
}
$helpers .= "?>";
return $helpers . $this
->toTree(file_get_contents($sourceFile))
->render();
}
private function toTree($source) {
$source = str_replace(array(
"\r\n",
"\n\r",
"\r",
), "\n", $source);
$this->source = explode("\n", $source);
$this
->setIndentChar();
preg_match_all(self::REGEX_HAML, $source, $this->source, PREG_SET_ORDER);
unset($source);
$root = new HamlRootNode(array(
'format' => $this->format,
'style' => $this->style,
'attrWrapper' => $this->attrWrapper,
'minimizedAttributes' => $this->minimizedAttributes,
));
$this
->buildTree($root);
return $root;
}
private function buildTree($parent) {
while (!empty($this->source) && $this
->isChildOf($parent, $this->source[0])) {
$line = $this
->getNextLine();
if (!empty($line)) {
$node = $this->inFilter ? new HamlNode($line[self::HAML_SOURCE], $parent) : $this
->parseLine($line, $parent);
if (!empty($node)) {
$node->token = $line;
$node->showOutput = $this->showOutput;
$node->showSource = $this->showSource;
$this
->addChildren($node, $line);
}
}
}
}
private function addChildren($node, $line) {
if ($node instanceof HamlFilterNode) {
$this->inFilter = true;
}
if ($this
->hasChild($line, $this->inFilter)) {
$this
->buildTree($node);
if ($node instanceof HamlFilterNode) {
$this->inFilter = false;
}
}
}
private function hasChild($line, $allowGreater = false) {
if (!empty($this->source)) {
$i = 0;
$c = count($this->source);
while (empty($nextLine[self::HAML_SOURCE]) && $i <= $c) {
$nextLine = $this->source[$i++];
}
$level = $this
->getLevel($nextLine, $line['line'] + $i);
if ($level == $line['level'] + 1 || $allowGreater && $level > $line['level']) {
return true;
}
elseif ($level <= $line['level']) {
return false;
}
else {
throw new HamlException('Illegal indentation level ({level}); indentation level can only increase by one', array(
'{level}' => $level,
), $this);
}
}
else {
return false;
}
}
private function isChildOf($node, $line) {
$haml = trim($line[self::HAML_HAML]);
return empty($haml) || $this
->getLevel($line, $this->line) > $node->level;
}
private function setIndentChar() {
foreach ($this->source as $l => $source) {
if (!empty($source) && in_array($source[0], $this->indentChars)) {
$this->indentChar = $source[0];
for ($i = 0, $len = strlen($source); $i < $len && $source[$i] == $this->indentChar; $i++) {
}
if ($i < $len && in_array($source[$i], $this->indentChars)) {
$this->line = ++$l;
$this->source = $source;
throw new HamlException('Mixed indentation not allowed', array(), $this);
}
$this->indentSpaces = $this->indentChar == ' ' ? $i : 1;
return;
}
}
$this->indentChar = ' ';
$this->indentSpaces = 2;
}
private function getNextLine() {
$line = array_shift($this->source);
$haml = trim($line[self::HAML_HAML]);
if (empty($haml)) {
$this->line++;
return null;
}
if ($line[self::HAML_WHITESPACE_REMOVAL] === self::INNER_WHITESPACE_REMOVAL && empty($line[self::HAML_TAG])) {
$line[self::HAML_CONTENT] = $line[self::HAML_WHITESPACE_REMOVAL] . $line[self::HAML_TOKEN] . $line[self::HAML_CONTENT];
}
if (!empty($line[self::HAML_OBJECT_REFERENCE]) && empty($line[self::HAML_TAG])) {
unset($line[self::HAML_OBJECT_REFERENCE]);
$line[self::HAML_CONTENT] = $line[self::HAML_SOURCE];
}
$line['line'] = $this->line++;
$line['level'] = $this
->getLevel($line, $this->line);
$line['filename'] = $this->filename;
if ($this
->isMultiline($line)) {
$line = $this
->getMultiline($line);
}
return $line;
}
private function getLevel($line, $n) {
if ($line[self::HAML_INDENT] && $this->indentChar === ' ') {
$indent = strlen($line[self::HAML_INDENT]) / $this->indentSpaces;
}
else {
$indent = strlen($line[self::HAML_INDENT]);
}
if (!is_integer($indent) || preg_match("/[^{$this->indentChar}]/", $line[self::HAML_INDENT])) {
throw new HamlException('Invalid indentation', array(), $this);
}
return $indent;
}
private function parseLine($line, $parent) {
if ($this
->isHamlComment($line)) {
return $this
->parseHamlComment($line);
}
elseif ($this
->isXmlComment($line)) {
return $this
->parseXmlComment($line, $parent);
}
elseif ($this
->isElement($line)) {
return $this
->parseElement($line, $parent);
}
elseif ($this
->isHelper($line)) {
return $this
->parseHelper($line, $parent);
}
elseif ($this
->isCode($line)) {
return $this
->parseCode($line, $parent);
}
elseif ($this
->isDirective($line)) {
return $this
->parseDirective($line, $parent);
}
elseif ($this
->isFilter($line)) {
return $this
->parseFilter($line, $parent);
}
elseif ($this
->isDoctype($line)) {
return $this
->parseDoctype($line, $parent);
}
else {
return $this
->parseContent($line, $parent);
}
}
private function hasContent($line) {
return !empty($line[self::HAML_CONTENT]);
}
private function isCode($line) {
return $line[self::HAML_TOKEN] === self::RUN_CODE;
}
private function isDirective($line) {
return $line[self::HAML_TOKEN] === self::DIRECTIVE;
}
private function isDoctype($line) {
return $line[self::HAML_TOKEN] === self::DOCTYPE;
}
private function isElement(&$line) {
if (empty($line[self::HAML_TAG]) && (!empty($line[self::HAML_CLASS]) || !empty($line[self::HAML_ID]) || !empty($line[self::HAML_XML_ATTRIBUTES]) || !empty($line[self::HAML_RUBY_ATTRIBUTES]) || !empty($line[self::HAML_OBJECT_REFERENCE]))) {
$line[self::HAML_TAG] = 'div';
}
return !empty($line[self::HAML_TAG]);
}
private function isFilter($line) {
return !empty($line[self::HAML_FILTER]);
}
private function isHamlComment($line) {
return preg_match(self::HAML_COMMENT, $line[self::HAML_TOKEN]) > 0;
}
private function isHelper($line) {
return preg_match(HamlHelperNode::MATCH, $line[self::HAML_CONTENT], $matches) ? method_exists($this->helperClass, $matches[HamlHelperNode::NAME]) : false;
}
private function isXmlComment($line) {
return $line[self::HAML_SOURCE][0] === self::XML_COMMENT;
}
private function isMultiline($line) {
return substr($line[self::HAML_SOURCE], -2) === self::MULTILINE;
}
private function isBlock($line) {
return !in_array($line[self::HAML_TAG], $this->inlineTags);
}
private function isSelfClosing($line) {
return in_array($line[self::HAML_TAG], $this->emptyTags) || $line[self::HAML_TOKEN] == self::SELF_CLOSE_TAG;
}
private function getFilter($filter) {
static $firstRun = true;
$imported = false;
if (empty($this->filters[$filter])) {
if ($firstRun) {
require_once 'filters/HamlBaseFilter.php';
$firstRun = false;
}
$filterclass = 'Haml' . ucfirst($filter) . 'Filter';
if (isset($this->filterDir)) {
$this->filterDir = substr($this->filterDir, -1) == DIRECTORY_SEPARATOR ? substr($this->filterDir, 0, -1) : $this->filterDir;
if (file_exists($this->filterDir . DIRECTORY_SEPARATOR . "{$filterclass}.php")) {
require_once $this->filterDir . DIRECTORY_SEPARATOR . "{$filterclass}.php";
$imported = true;
}
}
if (!$imported && file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'filters' . DIRECTORY_SEPARATOR . "{$filterclass}.php")) {
require_once "filters/{$filterclass}.php";
$imported = true;
}
if (!$imported) {
throw new HamlException('Unable to find {what}: {filename}', array(
'{what}' => $filter . ' filter',
'{filename}' => $filterclass . '.php',
), $this);
}
$this->filters[$filter] = new $filterclass();
if (!$this->filters[$filter] instanceof HamlBaseFilter) {
throw new HamlException('{what} must extend {base} class', array(
'{what}' => $filter,
'{base}' => 'HamlBaseFilter',
), $this);
}
$this->filters[$filter]
->init();
}
return $this->filters[$filter];
}
private function getMultiline($line) {
do {
$multiLine = array_shift($this->source);
$line[self::HAML_CONTENT] .= substr($multiLine[self::HAML_SOURCE], 0, -2);
} while (!empty($this->source) && $this
->isMultiline($this->source[0]));
return $line;
}
private function parseAttributes($line) {
$attributes = array();
if (!empty($line[self::HAML_OPEN_XML_ATTRIBUTES])) {
if (empty($line[self::HAML_XML_ATTRIBUTES])) {
$line[self::HAML_XML_ATTRIBUTES] = $line[self::HAML_CONTENT];
unset($line[self::HAML_CONTENT]);
do {
$multiLine = array_shift($this->source);
$line[self::HAML_XML_ATTRIBUTES] .= $multiLine[self::HAML_CONTENT];
} while (substr($line[self::HAML_XML_ATTRIBUTES], -1) !== self::CLOSE_XML_ATTRIBUTES);
}
if (preg_match(self::HTML_ATTRS, $line[self::HAML_XML_ATTRIBUTES], $htmlAttrs)) {
$line[self::HAML_XML_ATTRIBUTES] = preg_replace(self::HTML_ATTRS, '', $line[self::HAML_XML_ATTRIBUTES]);
$attributes = array_merge($attributes, $this
->htmlAttrs($htmlAttrs));
}
$attributes = array_merge($attributes, $this
->parseAttributeHash($line[self::HAML_XML_ATTRIBUTES]));
}
if (!empty($line[self::HAML_OPEN_RUBY_ATTRIBUTES])) {
if (empty($line[self::HAML_RUBY_ATTRIBUTES])) {
$line[self::HAML_RUBY_ATTRIBUTES] = $line[self::HAML_CONTENT];
unset($line[self::HAML_CONTENT]);
do {
$multiLine = array_shift($this->source);
$line[self::HAML_RUBY_ATTRIBUTES] .= $multiLine[self::HAML_CONTENT];
} while (substr($line[self::HAML_RUBY_ATTRIBUTES], -1) !== self::CLOSE_RUBY_ATTRIBUTES);
}
if (preg_match(self::HTML_ATTRS, $line[self::HAML_RUBY_ATTRIBUTES], $htmlAttrs)) {
$line[self::HAML_RUBY_ATTRIBUTES] = preg_replace(self::HTML_ATTRS, '', $line[self::HAML_RUBY_ATTRIBUTES]);
$attributes = array_merge($attributes, $this
->htmlAttrs($htmlAttrs));
}
$attributes = array_merge($attributes, $this
->parseAttributeHash($line[self::HAML_RUBY_ATTRIBUTES]));
}
if (!empty($line[self::HAML_OBJECT_REFERENCE])) {
$objectRef = explode(',', preg_replace('/,\\s*/', ',', $line[self::HAML_OBJECT_REFERENCE]));
$prefix = isset($objectRef[1]) ? $objectRef[1] . '_' : '';
$class = "strtolower(str_replace(' ',\t'_', preg_replace('/(?<=\\w)([ A-Z])/', '_\1', get_class(" . $objectRef[0] . '))))';
$attributes['class'] = "<?php echo '{$prefix}' . {$class}; ?>";
$attributes['id'] = "<?php echo '{$prefix}' . {$class} . '_' . {$objectRef[0]}->id; ?>";
}
else {
if (!empty($line[self::HAML_CLASS])) {
$classes = explode('.', $line[self::HAML_CLASS]);
foreach ($classes as &$class) {
if (preg_match(self::MATCH_INTERPOLATION, $class)) {
$class = $this
->interpolate($class);
}
}
$attributes['class'] = join(' ', $classes) . (isset($attributes['class']) ? " {$attributes['class']}" : '');
}
if (!empty($line[self::HAML_ID])) {
$attributes['id'] = (preg_match(self::MATCH_INTERPOLATION, $line[self::HAML_ID]) ? $this
->interpolate($line[self::HAML_ID]) : $line[self::HAML_ID]) . (isset($attributes['id']) ? "_{$attributes['id']}" : '');
}
}
ksort($attributes, SORT_STRING);
return $attributes;
}
private function parseAttributeHash($subject) {
$subject = substr($subject, 0, -1);
$attributes = array();
if (preg_match(self::REGEX_ATTRIBUTE_FUNCTION, $subject)) {
$attributes[0] = "<?php echo {$subject}; ?>";
return $attributes;
}
preg_match_all(self::REGEX_ATTRIBUTES, $subject, $attrs, PREG_SET_ORDER);
foreach ($attrs as $attr) {
if (!empty($attr[1])) {
$dataAttributes = $this
->parseAttributeHash(substr($attr[2], 1));
foreach ($dataAttributes as $key => $value) {
$attributes["data-{$key}"] = $value;
}
}
elseif (!empty($attr[4])) {
$values = array_map('trim', explode(',', $attr[4]));
if ($attr[3] !== 'class' && $attr[3] !== 'id') {
throw new HamlException('Attribute must be "class" or "id" with array value', array(), $this);
}
$attributes[$attr[3]] = '<?php echo ' . join($attr[3] === 'id' ? ".'_'." : ".' '.", $values) . '; ?>';
}
elseif (!empty($attr[6])) {
$attributes[$attr[3]] = $this
->interpolate($attr[6], $attr[3]);
}
else {
switch ($attr[7]) {
case 'true':
$attributes[$attr[3]] = $attr[3];
break;
case 'false':
break;
case '':
$attributes[$attr[3]] = "";
break;
default:
$attributes[$attr[3]] = "<?php echo {$attr[7]}; ?>";
break;
}
}
}
return $attributes;
}
private function htmlAttrs($htmlAttrs) {
if (empty($htmlAttrs[1]) && empty($htmlAttrs[2])) {
return HamlHelpers::html_attrs();
}
else {
$htmlAttrs[1] = substr($htmlAttrs[1], 1, -1);
if (substr($htmlAttrs[1], -1) == ';') {
$htmlAttrs[1] = eval("return {$htmlAttrs[1]}");
}
if (isset($htmlAttrs[2])) {
return HamlHelpers::html_attrs($htmlAttrs[1], eval($htmlAttrs[2] . ';'));
}
else {
return HamlHelpers::html_attrs($htmlAttrs[1]);
}
}
}
private function parseCode($line, $parent) {
if (preg_match('/^(if|foreach|for|switch|do|while)\\b(.*)$/', $line[self::HAML_CONTENT], $block)) {
if ($block[1] === 'do') {
$node = new HamlCodeBlockNode('<?php do { ?>', $parent);
$node->doWhile = 'while' . $block[2] . ';';
}
elseif ($block[1] === 'switch') {
$node = new HamlCodeBlockNode("<?php {$line[self::HAML_CONTENT]} {", $parent);
}
else {
$node = new HamlCodeBlockNode("<?php {$line[self::HAML_CONTENT]} { ?>", $parent);
}
}
elseif (strpos($line[self::HAML_CONTENT], 'else') === 0) {
$node = new HamlCodeBlockNode("<?php } {$line[self::HAML_CONTENT]} { ?>", null);
$node->token = $line;
$node->showOutput = $this->showOutput;
$node->showSource = $this->showSource;
$parent
->getLastChild()
->addElse($node);
$this
->addChildren($node, $line);
$node = null;
}
elseif (strpos($line[self::HAML_CONTENT], 'case') === 0) {
$node = new HamlNode(($parent
->hasChildren() ? '<?php ' : '') . "{$line[self::HAML_CONTENT]}: ?>", $parent);
}
else {
$node = new HamlNode("<?php {$line[self::HAML_CONTENT]}; ?>", $parent);
}
return $node;
}
private function parseContent($line, $parent) {
switch ($line[self::HAML_TOKEN]) {
case self::INSERT_CODE:
$content = $this->suppressEval ? '' : '<?php echo ' . ($this->escapeHtml ? 'htmlentities(' . $line[self::HAML_CONTENT] . ')' : $line[self::HAML_CONTENT]) . "; ?>" . ($this->style == HamlRenderer::STYLE_EXPANDED || $this->style == HamlRenderer::STYLE_NESTED ? "\n" : '');
break;
case self::INSERT_CODE_PRESERVE_WHITESPACE:
$content = $this->suppressEval ? '' : '<?php echo str_replace("\\n", \'
\', ' . ($this->escapeHtml ? 'htmlentities(' . $line[self::HAML_CONTENT] . ')' : $line[self::HAML_CONTENT]) . "; ?>" . ($this->style == HamlRenderer::STYLE_EXPANDED || $this->style == HamlRenderer::STYLE_NESTED ? "\n" : '');
break;
case self::UNESCAPE_XML:
$content = $this->suppressEval ? '' : '<?php echo ' . $line[self::HAML_CONTENT] . "; ?>" . ($this->style == HamlRenderer::STYLE_EXPANDED || $this->style == HamlRenderer::STYLE_NESTED ? "\n" : '');
break;
case self::ESCAPE_XML:
$content = $this->suppressEval ? '' : '<?php echo ' . ('htmlentities(' . $line[self::HAML_CONTENT] . ')') . "; ?>" . ($this->style == HamlRenderer::STYLE_EXPANDED || $this->style == HamlRenderer::STYLE_NESTED ? "\n" : '');
break;
default:
$content = $line[self::HAML_CONTENT];
break;
}
return new HamlNode($this
->interpolate($content), $parent);
}
private function parseDirective($line) {
preg_match('/(\\w+)(\\+|-)?/', $line[self::HAML_CONTENT], $matches);
switch ($matches[1]) {
case 's':
$this->showSource = $matches[2] == '+' ? true : ($matches[2] == '-' ? false : $this->showSource);
break;
case 'o':
$this->showOutput = $matches[2] == '+' ? true : ($matches[2] == '-' ? false : $this->showOutput);
break;
case 'os':
case 'so':
$this->showSource = $matches[2] == '+' ? true : ($matches[2] == '-' ? false : $this->showSource);
$this->showOutput = $matches[2] == '+' ? true : ($matches[2] == '-' ? false : $this->showOutput);
break;
default:
if (!in_array($matches[1], $this->styles)) {
throw new HamlException('Invalid {what} ({value})', array(
'{what}' => 'directive',
'{value}' => self::DIRECTIVE . $matches[0],
), $this);
}
$this->style = $matches[1];
break;
}
}
private function parseDoctype($line, $parent) {
$content = explode(' ', $line[self::HAML_CONTENT]);
if (!empty($content)) {
if ($content[0] === self::IS_XML_PROLOG) {
$encoding = isset($content[1]) ? $content[1] : self::DEFAULT_XML_ENCODING;
$output = str_replace(self::XML_ENCODING, $encoding, self::XML_PROLOG);
}
elseif (empty($content[0])) {
$output = $this->doctypes[$this->format][0];
}
elseif (array_key_exists($content[0], $this->doctypes[$this->format])) {
$output = $this->doctypes[$this->format][$content[0]];
}
elseif (!empty($this->doctype)) {
$output = $this->doctype;
}
else {
$_doctypes = array_keys($this->doctypes[$this->format]);
array_shift($_doctypes);
throw new HamlException('Invalid {what} ({value}); must be one of "{options}"', array(
'{what}' => 'doctype',
'{value}' => $content[0],
'{options}' => join(', ', $_doctypes) . ' or empty',
), $this);
}
}
return new HamlDoctypeNode($output, $parent);
}
private function parseHamlComment($line) {
if (!$this
->hasContent($line)) {
while ($this
->hasChild($line, true)) {
array_shift($this->source);
$this->line++;
}
}
}
private function parseHelper($line, $parent) {
preg_match(HamlHelperNode::MATCH, $line[self::HAML_CONTENT], $matches);
$node = new HamlHelperNode($this->helperClass, $matches[HamlHelperNode::PRE], $matches[HamlHelperNode::NAME], $matches[HamlHelperNode::ARGS], $parent);
if (isset($matches[HamlHelperNode::BLOCK])) {
new HamlNode($matches[HamlHelperNode::BLOCK], $node);
}
return $node;
}
private function parseElement($line, $parent) {
$node = new HamlElementNode($line[self::HAML_TAG], $parent);
$node->isSelfClosing = $this
->isSelfClosing($line);
$node->isBlock = $this
->isBlock($line);
$node->attributes = $this
->parseAttributes($line);
if ($this
->hasContent($line)) {
$child = $this
->parseContent($line, $node);
$child->showOutput = $this->showOutput;
$child->showSource = $this->showSource;
$child->token = array(
self::HAML_SOURCE => $line[self::HAML_SOURCE],
'filename' => $line['filename'],
'line' => $line['line'],
'level' => $line['level'] + 1,
);
}
$node->whitespaceControl = $this
->parseWhitespaceControl($line);
return $node;
}
private function parseFilter($line, $parent) {
$node = new HamlFilterNode($this
->getFilter($line[self::HAML_FILTER]), $parent);
if ($this
->hasContent($line)) {
$child = $this
->parseContent($line);
$child->showOutput = $this->showOutput;
$child->showSource = $this->showSource;
$child->token = array(
'level' => $line['level'] + 1,
'line' => $line['line'],
);
}
return $node;
}
private function parseXmlComment($line, $parent) {
return new HamlCommentNode($line[self::HAML_CONTENT], $parent);
}
private function parseWhitespaceControl($line) {
$whitespaceControl = array(
'inner' => false,
'outer' => array(
'left' => false,
'right' => false,
),
);
if (!empty($line[self::HAML_WHITESPACE_REMOVAL])) {
$whitespaceControl['inner'] = strpos($line[self::HAML_WHITESPACE_REMOVAL], self::INNER_WHITESPACE_REMOVAL) !== false;
if (strpos($line[self::HAML_WHITESPACE_REMOVAL], self::OUTER_WHITESPACE_REMOVAL) !== false) {
$whitespaceControl['outer']['left'] = strpos($line[self::HAML_WHITESPACE_REMOVAL], self::BLOCK_LEFT_OUTER_WHITESPACE_REMOVAL) === false;
$whitespaceControl['outer']['right'] = strpos($line[self::HAML_WHITESPACE_REMOVAL], self::BLOCK_RIGHT_OUTER_WHITESPACE_REMOVAL) === false;
}
}
return $whitespaceControl;
}
protected function interpolate($string, $type = '') {
return preg_replace(self::MATCH_INTERPOLATION, in_array($type, $this->minimizedAttributes) ? '\\1' : self::INTERPOLATE, $string);
}
}