Beispieler: eval nicht mit mehrdimensionalen Arrays möglich?

Beitrag lesen

Hallo,

hier mal ein einfaches Beispiel welches kein EVAL() verwendet und Dir evtl. sogar schon ausreichend die gewünschte Funktionalität als Basis liefert:

  
<?php  
class Template  
{  
    const VAR_PATTERN         = '~\[([^\]]+)\]~';  
    const COMMENT_FORMAT      = '/* %s */';  
    const PATH_DELIMITER      = '.';  
    const ATTRIBUTE_DELIMITER = ';';  
    const ATTRIBUTE_ASSIGN    = ':';  
    const ELEMENT_DELIMITER   = ' ';  
  
    public $vars = array();  
  
    protected function cbVarPattern($matches)  
    {  
        $path = array_reverse(explode(self::PATH_DELIMITER, $matches[1]));  
        $ref = & $this->vars;  
        while(!empty($path))  
        {  
            $element = array_pop($path);  
            if(isset($ref[$element]))  
            {  
                $ref = & $ref[$element];  
            }  
            else  
            {  
                // unbekannter array index - hier anfangen zu meckern...)  
                return sprintf(self::COMMENT_FORMAT, $matches[0]);  
                break;  
            }  
        }  
        return $this->escape($ref);  
    }  
  
    protected function escape($value)  
    {  
        if(is_array($value))  
        {  
            reset($value);  
            if(is_numeric(key($value)))  
            {  
                $value = implode(self::ELEMENT_DELIMITER, $value);  
            }  
            else  
            {  
                $temp = array();  
                foreach($value as $attrName => $attrValue)  
                {  
                    $temp[] = $attrName . self::ATTRIBUTE_ASSIGN . $attrValue;  
                }  
                $value = implode(self::ATTRIBUTE_DELIMITER, $temp);  
            }  
        }  
        return $value;  
    }  
  
    public function parse($content)  
    {  
        return preg_replace_callback(self::VAR_PATTERN, array($this, 'cbVarPattern'), $content);  
    }  
}  
$example = <<< VCSS  
        body { color:[example1.color]; }  
        div  { border:[example2]; }  
        p    { [example3] }  
        br   { margin:[example3.margin]; }  
        sup  { color:[some.more.nonsense]; }  
VCSS;  
$template = new Template();  
$template->vars['example1']['color'] = '#C0C0C0';  
$template->vars['example2'] = array('1px','solid','red');  
$template->vars['example3'] = array('font-size' => '1em', 'margin' => '1em');  
var_dump($template, $example, $template->parse($example));