Interpolation::render PHP Method

render() public method

public render ( )
    public function render()
    {
        if (!$this->_containsInterpolation($this->_text)) {
            return $this->_text;
        }
        $pieces = array();
        $glueL = $this->_phpCtx ? '.' : '<?php echo ';
        $glueR = $this->_phpCtx ? '.' : ' ?>';
        $encapsL = $this->_phpCtx ? '(' : '';
        $encapsR = $this->_phpCtx ? ')' : ';';
        $s = new StringScanner($this->_text);
        $quote = $s->scan(StringScanner::rQUOTE);
        while (!$s->eos) {
            trim($s->scan('/(.*?)(?<!\\\\)\\#\\{/sm'));
            if (!empty($s[1])) {
                $pieces[] = $quote . $s[1] . $quote;
            }
            trim($s->scan('/(.*?)(?<!\\\\)}/sm'));
            if (!empty($s[1])) {
                if ($this->_containsInterpolation($s[1])) {
                    throw new SyntaxErrorException("Nesting interpolation is not allowed: " . $this->_text);
                }
                $pieces[] = $glueL;
                $pieces[] = $encapsL . $s[1] . $encapsR;
                $pieces[] = $glueR;
            } else {
                throw new SyntaxErrorException("Unclosed interpolation in: " . $this->_text);
            }
            if (!$this->_containsInterpolation($s->rest)) {
                $rest = trim($s->scan('/.*/sm'), " {$quote}");
                if (!empty($rest)) {
                    $pieces[] = $quote . $rest . $quote;
                }
            }
        }
        if ($this->_phpCtx) {
            // can't have glue on the edges
            if ($pieces[0] == $glueL) {
                array_shift($pieces);
            }
            // can't have glue on the edges
            if ($pieces[count($pieces) - 1] == $glueR) {
                array_pop($pieces);
            }
            // don't nee the parenteses if it is only one thing
            if (count($pieces) == 1) {
                $pieces[0] = s($pieces[0])->trimBalanced('(', ')');
            }
        }
        return join($pieces);
    }

Usage Example

Example #1
0
 public function testRenderInsidePhp()
 {
     $i = new Interpolation("#{ImTheWholeThing()}", true);
     $actual = $i->render();
     $this->assertEquals('ImTheWholeThing()', $actual);
     $i = new Interpolation("\"Hey, look! #{ImInsidePhp()}! And #{\$me + \$too}!\"", true);
     $actual = $i->render();
     $this->assertEquals('"Hey, look! ".(ImInsidePhp())."! And ".($me + $too)."!"', $actual);
 }
All Usage Examples Of Interpolation::render