1<?php 2 3 4namespace ComboStrap; 5use Psr\Log\LogLevel; 6 7/** 8 * Class Template 9 * @package ComboStrap 10 * https://stackoverflow.com/questions/17869964/replacing-string-within-php-file 11 */ 12class Template 13{ 14 15 const VARIABLE_PREFIX = "$"; 16 const VARIABLE_PATTERN_CAPTURE_VARIABLE = "/(\\" . self::VARIABLE_PREFIX . "[\w]*)/im"; 17 const VARIABLE_PATTERN_CAPTURE_NAME = "/\\" . self::VARIABLE_PREFIX . "([\w]*)/im"; 18 19 protected $_string; 20 protected $_data = array(); 21 22 public function __construct($string = null) 23 { 24 $this->_string = $string; 25 } 26 27 /** 28 * @param $string 29 * @return Template 30 */ 31 public static function create($string) 32 { 33 return new Template($string); 34 } 35 36 public function set($key, $value) 37 { 38 $this->_data[$key] = $value; 39 return $this; 40 } 41 42 public function render(): string 43 { 44 45 46 $variablePattern = self::VARIABLE_PATTERN_CAPTURE_VARIABLE; 47 $splits = preg_split($variablePattern, $this->_string, -1, PREG_SPLIT_DELIM_CAPTURE); 48 $rendered = ""; 49 foreach ($splits as $part) { 50 if (substr($part, 0, 1) === self::VARIABLE_PREFIX) { 51 $variable = trim(substr($part, 1)); 52 if(isset($this->_data[$variable])) { 53 $value = $this->_data[$variable]; 54 } else { 55 LogUtility::msg("The variable ($variable) was not found and have not been replaced"); 56 $value = $variable; 57 } 58 } else { 59 $value = $part; 60 } 61 $rendered .= $value; 62 } 63 return $rendered; 64 65 } 66 67 /** 68 * 69 * @return false|string 70 * @deprecated Just for demo, don't use because the input is not validated 71 * 72 */ 73 public function renderViaEval() 74 { 75 extract($this->_data); 76 ob_start(); 77 eval("echo $this->_string ;"); 78 return ob_get_clean(); 79 } 80 81 /** 82 * @return array - an array of variable name 83 */ 84 public function getVariablesDetected(): array 85 { 86 $result = preg_match_all(self::VARIABLE_PATTERN_CAPTURE_NAME, $this->_string, $matches); 87 if ($result >= 1) { 88 return $matches[1]; 89 } else { 90 return []; 91 } 92 93 94 } 95} 96