<?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)
    {
        
// finds PHP code block and performs _replace only inside
        
$xhtml preg_replace_callback(
            
'@(<\?(=|\s|php\s)?(.*?)(\?>|$))@s',
            array(
$this'_replace'),
            
$xhtml
        
);
        
        return 
$xhtml;
    }

    protected function 
_replace($matches)
    {
        
$search = array(
            
// Helpers
            
'@\$this->([A-Z0-9_]+)\s*\(@is',
            
// Variables
            
'@\$this->([A-Z0-9_]+)@is',
            
// Any other reference
            
'@\$this@',
        );
        
$replace = array(
            
'$ctx->this->\\1(',
            
'$ctx->\\1',
            
'$ctx->this'
        
);

        
$xhtml preg_replace($search$replace$matches[1]);
        
        
// Ensure that the PHP block is closed, otherwise PHPTAL parser fails
        
if (substr($xhtml, -2) !== '?>') {
            
$xhtml .= '?>';
        }

        return 
$xhtml;
    }
}