|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * DynamicString template render |
| 5 | + * |
| 6 | + * @author Stefano Azzolini <lastguest@gmail.com> |
| 7 | + */ |
| 8 | + |
| 9 | +class DynamicString { |
| 10 | + |
| 11 | + protected $group_left, |
| 12 | + $group_right, |
| 13 | + $group_rx, |
| 14 | + $replacer; |
| 15 | + |
| 16 | + /** |
| 17 | + * Create a DynamicString instance for a specified group/separator |
| 18 | + * @param string $group A String containing an empty group envelope |
| 19 | + * @param string $separator The choice separator |
| 20 | + */ |
| 21 | + |
| 22 | + public function __construct($group='()', $separator='|'){ |
| 23 | + |
| 24 | + // Check if group delimiters are balanced. |
| 25 | + $l = strlen($group); |
| 26 | + if ($l%2) throw new Exception("Group delimiter must be balanced."); |
| 27 | + |
| 28 | + // Get left-right group delimiter |
| 29 | + list($this->group_left, $this->group_right) = str_split($group, $l>>1); |
| 30 | + |
| 31 | + // Build group regular expression |
| 32 | + $this->group_rx = |
| 33 | + "(\\".$this->group_left |
| 34 | + ."([^" |
| 35 | + .$this->group_left.$this->group_right |
| 36 | + ."]+)\\".$this->group_right |
| 37 | + .")x"; |
| 38 | + |
| 39 | + $this->replacer = function($m) use ($separator){ |
| 40 | + // Get one random choice |
| 41 | + $choice = array_rand($options = explode($separator, $m[1]),1); |
| 42 | + return $options[$choice]; |
| 43 | + }; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Render a new randomized instance of passed template. |
| 48 | + * @param string $template The generator template |
| 49 | + * @return string The random rendered version |
| 50 | + */ |
| 51 | + |
| 52 | + public function render($template){ |
| 53 | + |
| 54 | + // While there are groups, resolve them |
| 55 | + while (false !== strpos($template, $this->group_left)) { |
| 56 | + $template = preg_replace_callback($this->group_rx, $this->replacer, $template); |
| 57 | + } |
| 58 | + |
| 59 | + // Return rendered template |
| 60 | + return $template; |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments