back to devpro   download
<?php // 5

/** Experimental Script Handler for PHP
 * @author  Andrea Giammarchi
 * @site    webreflection.blogspot.com
 * @date    2008-04-15
 */
class PHPScriptHandler {

    # static public stuff
    static  public  function    init(){ # here starts the magic
        ob_start(array('PHPScriptHandler', 'handler'));
    }

    static  public  function    handler($output){
        if(@$dom = DOMDocument::loadHTML($output)){ # do you know a better way to avoid problems with nested text ? (was preg_replace_callback)
            foreach($dom->getElementsByTagName('script') as $node){
                if(strtolower($node->getAttribute('type')) === 'text/php'){
                    $node->setAttribute('type', 'text/javascript');
                    $node->replaceChild(new DOMText(PHP_EOL.self::parse($node->textContent).PHP_EOL), $node->firstChild);
                }
            }
            $output = $dom->saveHTML();
        }
        return  $output;
    }

    # private stuff
    static  private function    parse(){
        eval(func_get_arg(0)); # do you know a better way to avoid variable names conflicts during evaluation ?
        return  self::vars(get_defined_vars());
    }

    static  private function    vars($vars){
        foreach($vars as $key => $value) # do not worry about dollar function, in php you cannot have a variable called "$"
            $vars[$key] = '$'.$key.'='.json_encode($value).';';
        return  implode(PHP_EOL, $vars);
    }
}

# Handler initialization
PHPScriptHandler::init();
?>
back to devpro   download
Creative Commons License