Created
July 14, 2020 19:37
-
-
Save sebastiaanfranken/b76161e1a5af43e8939e17849a73324b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class StringTemplate | |
{ | |
/** | |
* The input / base string template to use. | |
* | |
* @param string|null | |
*/ | |
protected $template = null; | |
/** | |
* The values to replace in the input / base string. | |
* | |
* @param array | |
*/ | |
protected $replace = []; | |
/** | |
* Creates a new StringTemplate instance. | |
* | |
* @param string $template The input / base string. | |
* @param string ...$replace The values to replace in the $template string. | |
* @return void | |
*/ | |
public function __construct(string $template, string ...$replace) | |
{ | |
$this->template = $template; | |
$this->replace = $replace; | |
} | |
/** | |
* Checks if $key is given in $replace | |
* | |
* @param mixed $key | |
* @return bool | |
*/ | |
private function has($key) : boolean | |
{ | |
return array_key_exists($key, $this->replace); | |
} | |
/** | |
* Outputs the result | |
* | |
* @return string|null | |
*/ | |
public function output() : ?string | |
{ | |
$output = $this->template; | |
if(count($this->replace) > 0) | |
{ | |
foreach($this->replace as $key => $value) | |
{ | |
$output = str_replace('$(' . $key . ')', $value, $output); | |
} | |
} | |
return $output; | |
} | |
/** | |
* Outputs the class as a string. | |
* | |
* @see output() | |
* @return string | |
*/ | |
public function __toString() : string | |
{ | |
return $this->output(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment