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

namespace yii\smarty;

use Smarty;
use Yii;
use yii\helpers\ArrayHelper;
13
use yii\helpers\StringHelper;
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
use yii\helpers\Url;
use yii\web\View;

/**
 * Extension provides Yii-specific syntax for Smarty templates.
 *
 * @author Alexander Makarov <sam@rmcreative.ru>
 * @author Henrik Maier <hwmaier@gmail.com>
 */
class Extension
{
    /**
     * @var ViewRenderer
     */
    protected $viewRenderer;
    /**
     * @var Smarty
     */
    protected $smarty;

    /**
     * @param ViewRenderer $viewRenderer
     * @param Smarty $smarty
     */
    public function __construct($viewRenderer, $smarty)
    {
        $this->viewRenderer = $viewRenderer;
        $smarty = $this->smarty = $smarty;

        $smarty->registerPlugin('function', 'path', [$this, 'functionPath']);
        $smarty->registerPlugin('function', 'url', [$this, 'functionUrl']);
        $smarty->registerPlugin('function', 'set', [$this, 'functionSet']);
        $smarty->registerPlugin('function', 'meta', [$this, 'functionMeta']);
        $smarty->registerPlugin('function', 'registerJsFile', [$this, 'functionRegisterJsFile']);
        $smarty->registerPlugin('function', 'registerCssFile', [$this, 'functionRegisterCssFile']);
        $smarty->registerPlugin('block', 'title', [$this, 'blockTitle']);
        $smarty->registerPlugin('block', 'description', [$this, 'blockDescription']);
        $smarty->registerPlugin('block', 'registerJs', [$this, 'blockJavaScript']);
        $smarty->registerPlugin('block', 'registerCss', [$this, 'blockCss']);
        $smarty->registerPlugin('compiler', 'use', [$this, 'compilerUse']);
        $smarty->registerPlugin('modifier', 'void', [$this, 'modifierVoid']);
    }

    /**
     * Smarty template function to get relative URL for using in links
     *
     * Usage is the following:
     *
     * {path route='blog/view' alias=$post.alias user=$user.id}
     *
     * where route is Yii route and the rest of parameters are passed as is.
     *
     * @param array $params
     * @param \Smarty_Internal_Template $template
     *
     * @return string
     */
    public function functionPath($params, \Smarty_Internal_Template $template)
    {
        if (!isset($params['route'])) {
            trigger_error("path: missing 'route' parameter");
        }

        array_unshift($params, $params['route']) ;
        unset($params['route']);

        return Url::to($params, true);
    }

    /**
     * Smarty template function to get absolute URL for using in links
     *
     * Usage is the following:
     *
     * {path route='blog/view' alias=$post.alias user=$user.id}
     *
     * where route is Yii route and the rest of parameters are passed as is.
     *
     * @param array $params
     * @param \Smarty_Internal_Template $template
     *
     * @return string
     */
    public function functionUrl($params, \Smarty_Internal_Template $template)
    {
        if (!isset($params['route'])) {
            trigger_error("path: missing 'route' parameter");
        }

        array_unshift($params, $params['route']) ;
        unset($params['route']);

        return Url::to($params, true);
    }

    /**
     * Smarty compiler function plugin
     * Usage is the following:
     *
     * {use class="app\assets\AppAsset"}
     * {use class="yii\helpers\Html"}
     * {use class='yii\widgets\ActiveForm' type='block'}
     * {use class='@app\widgets\MyWidget' as='my_widget' type='function'}
     *
     * Supported attributes: class, as, type. Type defaults to 'static'.
     *
     * @param $params
     * @param \Smarty_Internal_Template $template
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function compilerUse($params, $template)
    {
        if (!isset($params['class'])) {
            trigger_error("use: missing 'class' parameter");
        }
        // Compiler plugin parameters may include quotes, so remove them
        foreach ($params as $key => $value) {
            $params[$key] = trim($value, '\'""');
        }

        $class = $params['class'];
136
        $alias = ArrayHelper::getValue($params, 'as', StringHelper::basename($params['class']));
137 138 139 140 141 142 143 144 145 146 147 148 149
        $type = ArrayHelper::getValue($params, 'type', 'static');

        // Register the class during compile time
        $this->smarty->registerClass($alias, $class);

        if ($type === 'block') {
            // Register widget tag during compile time
            $this->viewRenderer->widgets['blocks'][$alias] = $class;
            $this->smarty->registerPlugin('block', $alias, [$this->viewRenderer, '_widget_block__' . $alias]);

            // Inject code to re-register widget tag during run-time
            return <<<PHP
<?php
150 151
    \$viewRenderer=\$_smarty_tpl->default_template_handler_func[0];
    \$viewRenderer->widgets['blocks']['$alias'] = '$class';
152
    try {
153
        \$_smarty_tpl->registerPlugin('block', '$alias', [\$viewRenderer, '_widget_block__$alias']);
154 155 156 157 158 159 160 161 162 163 164 165 166 167
    }
    catch (SmartyException \$e) {
        /* Ignore already registered exception during first execution after compilation */
    }
?>
PHP;
        } elseif ($type === 'function') {
            // Register widget tag during compile time
            $this->viewRenderer->widgets['functions'][$alias] = $class;
            $this->smarty->registerPlugin('function', $alias, [$this->viewRenderer, '_widget_function__' . $alias]);

            // Inject code to re-register widget tag during run-time
            return <<<PHP
<?php
168 169
    \$viewRenderer=\$_smarty_tpl->default_template_handler_func[0];
    \$viewRenderer->widgets['functions']['$alias'] = '$class';
170
    try {
171
        \$_smarty_tpl->registerPlugin('function', '$alias', [\$viewRenderer, '_widget_function__$alias']);
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
    }
    catch (SmartyException \$e) {
        /* Ignore already registered exception during first execution after compilation */
    }
?>
PHP;
        }
    }

    /**
     * Smarty modifier plugin
     * Converts any output to void
     * @param mixed $arg
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function modifierVoid($arg)
    {
        return;
    }

    /**
     * Smarty function plugin
     * Usage is the following:
     *
     * {set title="My Page"}
     * {set theme="frontend"}
     * {set layout="main.tpl"}
     *
     * Supported attributes: title, theme, layout
     *
     * @param $params
     * @param \Smarty_Internal_Template $template
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function functionSet($params, $template)
    {
        if (isset($params['title'])) {
            $template->tpl_vars['this']->value->title = Yii::$app->getView()->title = ArrayHelper::remove($params, 'title');
        }
        if (isset($params['theme'])) {
            $template->tpl_vars['this']->value->theme = Yii::$app->getView()->theme = ArrayHelper::remove($params, 'theme');
        }
        if (isset($params['layout'])) {
            Yii::$app->controller->layout = ArrayHelper::remove($params, 'layout');
        }

        // We must have consumed all allowed parameters now, otherwise raise error
        if (!empty($params)) {
            trigger_error('set: Unsupported parameter attribute');
        }
    }

    /**
     * Smarty function plugin
     * Usage is the following:
     *
     * {meta keywords="Yii,PHP,Smarty,framework"}
     *
     * Supported attributes: any; all attributes are passed as
     * parameter array to Yii's registerMetaTag function.
     *
     * @param $params
     * @param \Smarty_Internal_Template $template
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function functionMeta($params, $template)
    {
        $key = isset($params['name']) ? $params['name'] : null;

        Yii::$app->getView()->registerMetaTag($params, $key);
    }

    /**
     * Smarty block function plugin
     * Usage is the following:
     *
     * {title} Web Site Login {/title}
     *
     * Supported attributes: none.
     *
     * @param $params
     * @param $content
     * @param \Smarty_Internal_Template $template
     * @param $repeat
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function blockTitle($params, $content, $template, &$repeat)
    {
        if ($content !== null) {
            Yii::$app->getView()->title = $content;
        }
    }

    /**
     * Smarty block function plugin
     * Usage is the following:
     *
     * {description}
     *     The text between the opening and closing tags is added as
     *     meta description tag to the page output.
     * {/description}
     *
     * Supported attributes: none.
     *
     * @param $params
     * @param $content
     * @param \Smarty_Internal_Template $template
     * @param $repeat
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function blockDescription($params, $content, $template, &$repeat)
    {
        if ($content !== null) {
            // Clean-up whitespace and newlines
            $content = preg_replace('/\s+/', ' ', trim($content));

            Yii::$app->getView()->registerMetaTag(['name' => 'description',
                                                   'content' => $content],
                                                   'description');
        }
    }

    /**
     * Smarty function plugin
     * Usage is the following:
     *
     * {registerJsFile url='http://maps.google.com/maps/api/js?sensor=false' position='POS_END'}
     *
     * Supported attributes: url, key, depends, position and valid HTML attributes for the script tag.
     * Refer to Yii documentation for details.
     * The position attribute is passed as text without the class prefix.
     * Default is 'POS_END'.
     *
     * @param $params
     * @param \Smarty_Internal_Template $template
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function functionRegisterJsFile($params, $template)
    {
        if (!isset($params['url'])) {
            trigger_error("registerJsFile: missing 'url' parameter");
        }

        $url = ArrayHelper::remove($params, 'url');
        $key = ArrayHelper::remove($params, 'key', null);
323
        $depends = ArrayHelper::remove($params, 'depends', null);
324 325 326
        if (isset($params['position']))
            $params['position'] = $this->getViewConstVal($params['position'], View::POS_END);

327
        Yii::$app->getView()->registerJsFile($url, $depends, $params, $key);
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    }

    /**
     * Smarty block function plugin
     * Usage is the following:
     *
     * {registerJs key='show' position='POS_LOAD'}
     *     $("span.show").replaceWith('<div class="show">');
     * {/registerJs}
     *
     * Supported attributes: key, position. Refer to Yii documentation for details.
     * The position attribute is passed as text without the class prefix.
     * Default is 'POS_READY'.
     *
     * @param $params
     * @param $content
     * @param \Smarty_Internal_Template $template
     * @param $repeat
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function blockJavaScript($params, $content, $template, &$repeat)
    {
        if ($content !== null) {
            $key = isset($params['key']) ? $params['key'] : null;
            $position = isset($params['position']) ? $params['position'] : null;

            Yii::$app->getView()->registerJs($content,
                                             $this->getViewConstVal($position, View::POS_READY),
                                             $key);
        }
    }

    /**
     * Smarty function plugin
     * Usage is the following:
     *
     * {registerCssFile url='@assets/css/normalizer.css'}
     *
     * Supported attributes: url, key, depends and valid HTML attributes for the link tag.
     * Refer to Yii documentation for details.
     *
     * @param $params
     * @param \Smarty_Internal_Template $template
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function functionRegisterCssFile($params, $template)
    {
        if (!isset($params['url'])) {
            trigger_error("registerCssFile: missing 'url' parameter");
        }

        $url = ArrayHelper::remove($params, 'url');
        $key = ArrayHelper::remove($params, 'key', null);
383
        $depends = ArrayHelper::remove($params, 'depends', null);
384

385
        Yii::$app->getView()->registerCssFile($url, $depends, $params, $key);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    }

    /**
     * Smarty block function plugin
     * Usage is the following:
     *
     * {registerCss}
     * div.header {
     *     background-color: #3366bd;
     *     color: white;
     * }
     * {/registerCss}
     *
     * Supported attributes: key and valid HTML attributes for the style tag.
     * Refer to Yii documentation for details.
     *
     * @param $params
     * @param $content
     * @param \Smarty_Internal_Template $template
     * @param $repeat
     * @return string
     * @note Even though this method is public it should not be called directly.
     */
    public function blockCss($params, $content, $template, &$repeat)
    {
        if ($content !== null) {
            $key = isset($params['key']) ? $params['key'] : null;

            Yii::$app->getView()->registerCss($content, $params, $key);
        }
    }

    /**
    * Helper function to convert a textual constant identifier to a View class
    * integer constant value.
    *
    * @param string $string Constant identifier name
    * @param integer $default Default value
    * @return mixed
    */
   protected function getViewConstVal($string, $default)
   {
      $val = @constant('yii\web\View::' . $string);
      return isset($val) ? $val : $default;
   }
Qiang Xue committed
431
}