Twig::addFunction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
3
/**
4
 * View\Twig
5
 *
6
 * Core\View Twig Bridge.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @version 1.0
11
 * @copyright Caffeina srl - 2014 - http://caffeina.co
12
 */
13
14
namespace View;
15
16
class Twig implements Adapter {
17
    protected static $loader = null;
18
    protected static $templatePath = '';
19
    protected static $twig = null;
20
    const EXTENSION = '.twig';
21
22
    public function __construct($path=null,$options=[]){
23
      static::$templatePath = rtrim($path,'/').'/';
24
      static::$loader = new \Twig_Loader_Filesystem($path);
25
      static::$twig   = new \Twig_Environment(static::$loader,$options);
26
    }
27
28
    public function __call($n,$p){
29
      return call_user_func_array([static::$twig,$n],$p);
30
    }
31
32
    public static function __callStatic($n,$p){
33
      return forward_static_call_array([static::$twig,$n],$p);
34
    }
35
36
    public function render($template,$data=[]){
37
    	try {
38
        return static::$twig->render($template.static::EXTENSION,$data);
39
      } catch(\Exception $e) {
40
      	return "<!-- ERROR --><pre class=\"error\"><code>$e</code></pre><!-- /ERROR -->";
41
      }
42
    }
43
44
    public static function exists($path){
45
        return is_file(static::$templatePath.$path.static::EXTENSION);
46
    }
47
48
    public static function addGlobal($key,$val){
49
      static::$twig->addGlobal($key,$val);
50
    }
51
52
    public static function addGlobals(array $defs){
53
      foreach ((array)$defs as $key=>$val) {
54
        static::$twig->addGlobal($key,$val);
55
      }
56
    }
57
58
    public static function addFilter($name,callable $filter){
59
      static::$twig->addFilter(new \Twig_SimpleFilter($name, $filter));
60
    }
61
62
    public static function addFunction($name,callable $function){
63
      static::$twig->addFunction(new \Twig_SimpleFunction($name, $function));
64
    }
65
66
    public static function addFilters(array $defs){
67
      foreach ((array)$defs as $key=>$val){
68
        if (is_callable($val)){
69
          static::$twig->addFilter(new \Twig_SimpleFilter($key, $val));
70
        }
71
      }
72
    }
73
74
}
75