Extension.php 5.4 KB
Newer Older
1 2 3 4 5 6 7 8
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\twig;
9

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
use yii\base\InvalidCallException;
use yii\helpers\Inflector;
use yii\helpers\StringHelper;
use yii\helpers\Url;

/**
 * Extension provides Yii-specific syntax for Twig templates.
 *
 * @author Andrey Grachov <andrey.grachov@gmail.com>
 * @author Alexander Makarov <sam@rmcreative.ru>
 */
class Extension extends \Twig_Extension
{
    /**
     * @var array used namespaces
     */
    protected $namespaces = [];

    /**
     * @var array used class aliases
     */
    protected $aliases = [];

    /**
     * @var array used widgets
     */
    protected $widgets = [];

    /**
     * Creates new instance
     *
     * @param array $uses namespaces and classes to use in the template
     */
    public function __construct(array $uses = [])
    {
        $this->addUses($uses);
    }

    /**
     * @inheritdoc
     */
    public function getNodeVisitors()
    {
        return [
            new Optimizer(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function getFunctions()
    {
        $options = [
            'is_safe' => ['html'],
        ];
        $functions = [
            new \Twig_SimpleFunction('use', [$this, 'addUses'], $options),
            new \Twig_SimpleFunction('*_begin', [$this, 'beginWidget'], $options),
            new \Twig_SimpleFunction('*_end', [$this, 'endWidget'], $options),
            new \Twig_SimpleFunction('widget_end', [$this, 'endWidget'], $options),
            new \Twig_SimpleFunction('*_widget', [$this, 'widget'], $options),
            new \Twig_SimpleFunction('path', [$this, 'path']),
            new \Twig_SimpleFunction('url', [$this, 'url']),
            new \Twig_SimpleFunction('void', function(){}),
        ];

        $options = array_merge($options, [
            'needs_context' => true,
        ]);
        $functions[] = new \Twig_SimpleFunction('register_*', [$this, 'registerAsset'], $options);
        foreach (['begin_page', 'end_page', 'begin_body', 'end_body', 'head'] as $helper) {
            $functions[] = new \Twig_SimpleFunction($helper, [$this, 'viewHelper'], $options);
        }
        return $functions;
    }

    public function registerAsset($context, $asset)
    {
        return $this->resolveAndCall($asset, 'register', [
            isset($context['this']) ? $context['this'] : null,
        ]);
    }

    public function beginWidget($widget, $config = [])
    {
        $widget = $this->resolveClassName($widget);
        $this->widgets[] = $widget;
        return $this->call($widget, 'begin', [
            $config,
        ]);
    }

    public function endWidget($widget = null)
    {
        if ($widget === null) {
            if (empty($this->widgets)) {
                throw new InvalidCallException('Unexpected end_widget() call. A matching begin_widget() is not found.');
            }
            $this->call(array_pop($this->widgets), 'end');
        } else {
            array_pop($this->widgets);
            $this->resolveAndCall($widget, 'end');
        }
    }

    public function widget($widget, $config = [])
    {
        return $this->resolveAndCall($widget, 'widget', [
            $config,
        ]);
    }

    public function viewHelper($context, $name = null)
    {
        if ($name !== null && isset($context['this'])) {
            $this->call($context['this'], Inflector::variablize($name));
        }
    }

    public function resolveAndCall($className, $method, $arguments = null)
    {
        return $this->call($this->resolveClassName($className), $method, $arguments);
    }

    public function call($className, $method, $arguments = null)
    {
        $callable = [$className, $method];
        if ($arguments === null) {
            return call_user_func($callable);
        } else {
            return call_user_func_array($callable, $arguments);
        }
    }

    public function resolveClassName($className)
    {
        $className = Inflector::id2camel($className, '_');
        if (isset($this->aliases[$className])) {
            return $this->aliases[$className];
        }
        $resolvedClassName = null;
        foreach ($this->namespaces as $namespace) {
            $resolvedClassName = $namespace . '\\' . $className;
            if (class_exists($resolvedClassName)) {
                return $this->aliases[$className] = $resolvedClassName;
            }
        }
        return $className;
    }

    public function addUses($args)
    {
        foreach ((array)$args as $key => $value) {
            $value = str_replace('/', '\\', $value);
            if (is_int($key)) {
                // namespace or class import
                if (class_exists($value)) {
                    // class import
                    $this->aliases[StringHelper::basename($value)] = $value;
                } else {
                    // namespace
                    $this->namespaces[] = $value;
                }
            } else {
                // aliased class import
                $this->aliases[$key] = $value;
            }
        }
    }

    public function path($path, $args = [])
    {
        return Url::to(array_merge([$path], $args));
    }

    public function url($path, $args = [])
    {
        return Url::to(array_merge([$path], $args), true);
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
196
        return 'yii2-twig';
197 198
    }
}