Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function format(string $format, array $tokens): string
- {
- $prev = '';
- $tag = '';
- $nextCond = [];
- $context = 'out'; // out, start, end, in
- $escapees = '{?}';
- $result = '';
- $escaped = $prevEscaped = false;
- //Lotta spaghetti... There's gotta be a way to simplify the conditions. Right?
- for ($i = 0; $i < strlen($format); $i++) {
- $ch = $format[$i];
- $prevEscaped = $escaped;
- if (strpos($escapees, $ch) !== false && $i>0 && $format[$i-1] === '\\') {
- $escaped = true;
- } else {
- $escaped = false;
- if ($ch === '\\' && strlen($format) > $i+1 && strpos($escapees, $format[$i+1]) !== false) continue;
- }
- if ($context === 'start') {
- if ($ch === '{') $result .= '{';
- else $context = 'in';
- }
- if ($format[$i] === '{' && !$escaped && $context === 'out') {
- $context = 'start';
- continue;
- } elseif ($format[$i] === '}' && !$escaped && ($context === 'in' || $context === 'inc')) {
- $context = 'end';
- }
- if ($context === 'end') {
- if ($format[$i-1] === '?' && !$prevEscaped) {
- $nextCond[] = $tag;
- $nextCond[] = '';
- } else {
- foreach ($nextCond as $item) {
- if ($item[-1] === '?') {
- if (array_key_exists($tag, $tokens) && !empty($tokens[$tag])) {
- if ($item[0] === '?') {
- if (array_key_exists($prev, $tokens) && !empty($tokens[$prev]))
- $result .= substr($item, 1, strlen($item)-1);
- }
- else $result .= substr($item, 0, strlen($item)-1);
- }
- }
- else $result .= $item;
- }
- $nextCond = [];
- }
- if ($tag[0] !== '?' && $tag[-1] !== '?') {
- if (array_key_exists($tag, $tokens))
- $result .= $tokens[$tag];
- $prev = $tag;
- } elseif ($tag[0] === '?' && ($tag[-1] !== '?' || $prevEscaped) && array_key_exists($prev, $tokens) && !empty($tokens[$prev])) {
- $result .= substr($tag, 1);
- }
- $context = 'out';
- $tag = '';
- continue;
- }
- if ($context === 'in') {
- $tag .= $format[$i];
- }
- if ($context === 'out') {
- if (!empty($nextCond))
- $nextCond[count($nextCond)-1] .= $ch;
- else $result .= $ch;
- }
- }
- return $result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement