<?php
abstract class Core_Twig_Template extends Twig_Template
{
    // XXX: array_merge_recursive() is crashing PHP 5.2.17
    // we need to figure out a workaround for this
    // it is only needed for FirePHP anyway
    public $context;

    public function render(array $context)
    {
        // merge Twig globals with local ones set from module feature
        // $globals       = $this->env->getGlobals();
        // $this->context = array_merge_recursive($globals, $context);
        $this->context = $context;

        return parent::render($context);
    }

    public function getCall($macro)
    {
        $macro_args = array();
        if (null !== strpos($macro, '(') && preg_match('/^(?P<macro>[a-zA-Z0-9_-]*)\s*\((?P<args>.*)\)\s*$/', trim($macro), $matches)) {
            // HACK HACK HACK HACK
            // extract macro arguments in Twig notation
            $env        = $this->getEnvironment();
            $node       = $env->parse($env->tokenize('{{ _self.dummy('. $matches['args'] .') }}'));
            $compiler   = new Twig_Compiler($this->getEnvironment());
            $node->getNode('body')->getNode(0)->getNode('expr')->getNode('arguments')->compile($compiler);
            $macro      = trim($matches['macro']);
            $macro_args = eval('return '. $compiler->getSource() .';');
        }

        $callback = array($this, 'get'. $macro);
        if (is_callable($callback)) {
            // this is a valid macro, call it!
            $args = func_get_args();
            array_shift($args);
            $args = array_merge($args, $macro_args);

            return call_user_func_array($callback, $args);
        } else {
            // throw new InvalidArgumentException(sprintf('Method "%s" for object "%s" does not exist.', 'get'. $macro, get_class($this)));
            throw new InvalidArgumentException(sprintf('Twig macro "%s()" not found!', $macro));
        }
    }

    public function setGlobal($name, $value)
    {
        $this->env->addGlobal($name, $value);
    }
}