xref: /plugin/combo/ComboStrap/Template.php (revision 37748cd8654635afbeca80942126742f0f4cc346)
1<?php
2
3
4namespace ComboStrap;
5/**
6 * Class Template
7 * @package ComboStrap
8 * https://stackoverflow.com/questions/17869964/replacing-string-within-php-file
9 */
10class Template
11{
12
13    const VARIABLE_PREFIX = "$";
14    protected $_string;
15    protected $_data = array();
16
17    public function __construct($string = null)
18    {
19        $this->_string = $string;
20    }
21
22    /**
23     * @param $string
24     * @return Template
25     */
26    public static function create($string)
27    {
28        return new Template($string);
29    }
30
31    public function set($key, $value)
32    {
33        $this->_data[$key] = $value;
34        return $this;
35    }
36
37    public function render()
38    {
39
40        $splits = preg_split("/(\\".self::VARIABLE_PREFIX."[\w]*)/",$this->_string,-1,PREG_SPLIT_DELIM_CAPTURE);
41        $rendered = "";
42        foreach($splits as $part){
43            if(substr($part,0,1)==self::VARIABLE_PREFIX){
44                $variable = trim(substr($part,1));
45                $value = $this->_data[$variable];
46            } else {
47                $value = $part;
48            }
49            $rendered .= $value;
50        }
51        return $rendered;
52
53    }
54
55    /**
56     *
57     * @return false|string
58     * @deprecated Just for demo, don't use because the input is not validated
59     *
60     */
61    public function renderViaEval()
62    {
63        extract($this->_data);
64        ob_start();
65        eval("echo $this->_string ;");
66        return ob_get_clean();
67    }
68}
69