1 | <?php |
||
7 | class Placeholders |
||
8 | { |
||
9 | protected $replacements = []; |
||
10 | protected $config = []; |
||
11 | protected $start; |
||
12 | protected $end; |
||
13 | protected $thorough; |
||
14 | |||
15 | 21 | public function __construct($config = []) |
|
19 | |||
20 | /** |
||
21 | * Sets a global replacement for a placeholder |
||
22 | * @param string $string The placeholder to set a value for |
||
23 | * @param mixed $value The value to replace it with |
||
24 | */ |
||
25 | 6 | public function set($string, $value) |
|
29 | |||
30 | /** |
||
31 | * Checks a string for placeholders and then replaces them with the appropriate values |
||
32 | * @param string $string A string containing placeholders |
||
33 | * @param array $replacements An array of key/value replacements |
||
34 | * @return string The new string |
||
35 | */ |
||
36 | 18 | public function parse($string, $replacements = []) |
|
37 | { |
||
38 | 18 | $replacements = array_merge($this->replacements, $replacements); |
|
39 | 18 | foreach ($replacements as $key => $val) { |
|
40 | 12 | $string = str_ireplace($this->getStart().$key.$this->getEnd(), $val, $string); |
|
41 | 18 | } |
|
42 | |||
43 | 18 | $this->catchSkippedPlaceholders($string); |
|
44 | |||
45 | 15 | return $string; |
|
46 | } |
||
47 | |||
48 | /** |
||
49 | * Checks for any placeholders that are in the |
||
50 | * string and then throws an Exception if one exists |
||
51 | * @param string $string The string to check |
||
52 | */ |
||
53 | 18 | protected function catchSkippedPlaceholders($string) |
|
54 | { |
||
55 | 18 | if ($this->getThorough() === true) { |
|
56 | 15 | $matches = []; |
|
57 | 15 | $pattern = "/".$this->getStart(true).".*?".$this->getEnd(true)."/"; |
|
58 | 15 | preg_match($pattern, $string, $matches); |
|
59 | |||
60 | 15 | if (count($matches) > 0) { |
|
61 | 3 | throw new Exception("Could not find a replacement for ".$matches[0], 1); |
|
62 | } |
||
63 | 12 | } |
|
64 | 15 | } |
|
65 | |||
66 | 3 | public function setStyle($start, $end) |
|
67 | { |
||
68 | 3 | $this->setStart($start); |
|
69 | 3 | $this->setEnd($end); |
|
70 | 3 | } |
|
71 | |||
72 | 3 | public function setThorough($x) |
|
76 | |||
77 | 3 | public function setStart($x) |
|
81 | |||
82 | 3 | public function setEnd($x) |
|
86 | |||
87 | 18 | public function getThorough() |
|
88 | { |
||
89 | 18 | return isset($this->thorough) ? $this->thorough : $this->config['thorough']; |
|
90 | } |
||
91 | |||
92 | 15 | public function getStart($escaped = false) |
|
97 | |||
98 | 15 | public function getEnd($escaped = false) |
|
103 | } |
||
104 |