1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace N98\Util\Template; |
4
|
|
|
|
5
|
|
|
use Twig_Environment; |
6
|
|
|
use Twig_Loader_Filesystem; |
7
|
|
|
use Twig_Loader_String; |
8
|
|
|
use Twig_Extension_Debug; |
9
|
|
|
use Twig_SimpleFilter; |
10
|
|
|
|
11
|
|
|
class Twig |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var \Twig_Environment |
15
|
|
|
*/ |
16
|
|
|
protected $twigEnv; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param array $baseDirs |
20
|
|
|
*/ |
21
|
|
|
public function __construct(array $baseDirs) |
22
|
|
|
{ |
23
|
|
|
$loader = new Twig_Loader_Filesystem($baseDirs); |
24
|
|
|
$this->twigEnv = new Twig_Environment($loader, array('debug' => true)); |
25
|
|
|
$this->addExtensions($this->twigEnv); |
26
|
|
|
$this->addFilters($this->twigEnv); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param string $filename |
31
|
|
|
* @param array $variables |
32
|
|
|
* |
33
|
|
|
* @return string |
34
|
|
|
*/ |
35
|
|
|
public function render($filename, $variables) |
36
|
|
|
{ |
37
|
|
|
return $this->twigEnv->render($filename, $variables); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @param string $string |
42
|
|
|
* @param array $variables |
43
|
|
|
* |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function renderString($string, $variables) |
47
|
|
|
{ |
48
|
|
|
$loader = new Twig_Loader_String(); |
|
|
|
|
49
|
|
|
$twig = new Twig_Environment($loader, array('debug' => true)); |
50
|
|
|
$this->addExtensions($twig); |
51
|
|
|
$this->addFilters($twig); |
52
|
|
|
|
53
|
|
|
return $twig->render($string, $variables); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param Twig_Environment $twig |
58
|
|
|
*/ |
59
|
|
|
protected function addFilters(Twig_Environment $twig) |
60
|
|
|
{ |
61
|
|
|
/** |
62
|
|
|
* cast_to_array |
63
|
|
|
*/ |
64
|
|
|
$twig->addFilter( |
65
|
|
|
new Twig_SimpleFilter('cast_to_array', array($this, 'filterCastToArray')) |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param Twig_Environment $twig |
71
|
|
|
*/ |
72
|
|
|
protected function addExtensions(Twig_Environment $twig) |
73
|
|
|
{ |
74
|
|
|
$twig->addExtension(new Twig_Extension_Debug()); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @param stdClass $stdClassObject |
79
|
|
|
* |
80
|
|
|
* @return array |
81
|
|
|
*/ |
82
|
|
|
public static function filterCastToArray($stdClassObject) |
83
|
|
|
{ |
84
|
|
|
if (is_object($stdClassObject)) { |
85
|
|
|
$stdClassObject = get_object_vars($stdClassObject); |
86
|
|
|
} |
87
|
|
|
if (is_array($stdClassObject)) { |
88
|
|
|
return array_map(__METHOD__, $stdClassObject); |
89
|
|
|
} else { |
90
|
|
|
return $stdClassObject; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.
The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.