1: <?php
2:
3: namespace WebLoader\Filter;
4:
5: /**
6: * Variables filter for WebLoader
7: *
8: * @author Jan Marek
9: * @license MIT
10: */
11: class VariablesFilter
12: {
13:
14: /** @var string */
15: private $startVariable = '{{$';
16:
17: /** @var string */
18: private $endVariable = '}}';
19:
20: /** @var array */
21: private $variables;
22:
23: /**
24: * Construct
25: * @param array $variables
26: */
27: public function __construct(array $variables = array())
28: {
29: foreach ($variables as $key => $value) {
30: $this->$key = $value;
31: }
32: }
33:
34: /**
35: * Set delimiter
36: * @param string $start
37: * @param string $end
38: * @return VariablesFilter
39: */
40: public function setDelimiter($start, $end)
41: {
42: $this->startVariable = (string)$start;
43: $this->endVariable = (string)$end;
44: return $this;
45: }
46:
47: /**
48: * Invoke filter
49: * @param string $code
50: * @return string
51: */
52: public function __invoke($code)
53: {
54: $start = $this->startVariable;
55: $end = $this->endVariable;
56:
57: $variables = array_map(function ($key) use ($start, $end) {
58: return $start . $key . $end;
59: }, array_keys($this->variables));
60:
61: $values = array_values($this->variables);
62:
63: return str_replace($variables, $values, $code);
64: }
65:
66: /**
67: * Magic set variable, do not call directly
68: * @param string $name
69: * @param string $value
70: */
71: public function __set($name, $value)
72: {
73: $this->variables[$name] = (string) $value;
74: }
75:
76: /**
77: * Magic get variable, do not call directly
78: * @param string $name
79: * @return string
80: * @throws \WebLoader\InvalidArgumentException
81: */
82: public function & __get($name)
83: {
84: if (array_key_exists($name, $this->variables)) {
85: return $this->variables[$name];
86: } else {
87: throw new \WebLoader\InvalidArgumentException("Variable '$name' is not set.");
88: }
89: }
90:
91: }