<?php
/**
 * PHPTAL Filter
 * Fixes Zend_View inline PHP to use with PHPTAL
 * @version 1.2
 */
class ZFSyntax implements PHPTAL_Filter {

    
/**
     * String filtering method, returns filtered string
     *
     * @name filter
     * @access public
     * @param string $xhtml Input code
     * @return string Filtered code
     * @author TAAT
     * @author Romke van der Meulen (regex fixes)
     */
    
public function filter($xhtml)
    {
        
// Uses PHP lexycal tokenizer to parse the template source
        
$tokens token_get_all($xhtml);

        
$xhtml = array();
        
$isPhp false;
        foreach (
$tokens as $token) {
            if (
is_string($token)) {
                
$xhtml[] = $token;
            } else {
                switch (
$token[0]) {
                    case 
T_OPEN_TAG:
                    case 
T_OPEN_TAG_WITH_ECHO:
                        
$isPhp true;
                    break;
                    case 
T_CLOSE_TAG:
                        
$isPhp false;
                    break;
                    case 
T_VARIABLE:
                        if (
$token[1] === '$this') {
                            
$token[1] = '$ctx->this';
                        }
                    break;
                }

                
$xhtml[] = $token[1];
            }
        }

        
// Make sure the last php block is closed
        
if ($isPhp) {
            
$xhtml[] = '?>';
        }

        return 
implode(''$xhtml);
    }
}