Completed
Push — develop ( c1861f...657930 )
by Kenji
06:24
created

Twig::addGlobal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
/**
3
 * Part of CodeIgniter Simple and Secure Twig
4
 *
5
 * @author     Kenji Suzuki <https://github.com/kenjis>
6
 * @license    MIT License
7
 * @copyright  2015 Kenji Suzuki
8
 * @link       https://github.com/kenjis/codeigniter-ss-twig
9
 */
10
11
// If you don't use Composer, uncomment below
12
/*
13
require_once APPPATH . 'third_party/Twig-1.xx.x/lib/Twig/Autoloader.php';
14
Twig_Autoloader::register();
15
*/
16
17
class Twig
18
{
19
	private $config = [];
20
21
	private $functions_asis = [
22
		'base_url', 'site_url'
23
	];
24
	private $functions_safe = [
25
		'form_open', 'form_close', 'form_error', 'set_value', 'form_hidden'
26
	];
27
28
	/**
29
	 * @var bool Whether functions are added or not
30
	 */
31
	private $functions_added = FALSE;
32
33
	/**
34
	 * @var Twig_Environment
35
	 */
36
	private $twig;
37
38
	/**
39
	 * @var Twig_Loader_Filesystem
40
	 */
41
	private $loader;
42
43
	public function __construct($params = [])
44
	{
45
		// default config
46
		$this->config = [
47
			'paths' => [VIEWPATH],
48
			'cache' => APPPATH . '/cache/twig',
49
		];
50
51
		$this->config = array_merge($this->config, $params);
52
53 View Code Duplication
		if (isset($params['functions']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
54
		{
55
			$this->functions_asis = 
56
				array_unique(
57
					array_merge($this->functions_asis, $params['functions'])
58
				);
59
		}
60 View Code Duplication
		if (isset($params['functions_safe']))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
		{
62
			$this->functions_safe = 
63
				array_unique(
64
					array_merge($this->functions_safe, $params['functions_safe'])
65
				);
66
		}
67
	}
68
69
	protected function resetTwig()
70
	{
71
		$this->twig = null;
72
		$this->createTwig();
73
	}
74
75
	protected function createTwig()
76
	{
77
		// $this->twig is singleton
78
		if ($this->twig !== null)
79
		{
80
			return;
81
		}
82
83
		if (ENVIRONMENT === 'production')
84
		{
85
			$debug = FALSE;
86
		}
87
		else
88
		{
89
			$debug = TRUE;
90
		}
91
92
		if ($this->loader === null)
93
		{
94
			$this->loader = new \Twig_Loader_Filesystem($this->config['paths']);
95
		}
96
97
		$twig = new \Twig_Environment($this->loader, [
98
			'cache'      => $this->config['cache'],
99
			'debug'      => $debug,
100
			'autoescape' => TRUE,
101
		]);
102
103
		if ($debug)
104
		{
105
			$twig->addExtension(new \Twig_Extension_Debug());
106
		}
107
108
		$this->twig = $twig;
109
	}
110
111
	protected function setLoader($loader)
112
	{
113
		$this->loader = $loader;
114
	}
115
116
	/**
117
	 * Registers a Global
118
	 * 
119
	 * @param string $name  The global name
120
	 * @param mixed  $value The global value
121
	 */
122
	public function addGlobal($name, $value)
123
	{
124
		$this->createTwig();
125
		$this->twig->addGlobal($name, $value);
126
	}
127
128
	/**
129
	 * Renders Twig Template and Set Output
130
	 * 
131
	 * @param string $view   Template filename without `.twig`
132
	 * @param array  $params Array of parameters to pass to the template
133
	 */
134
	public function display($view, $params = [])
135
	{
136
		$CI =& get_instance();
137
		$CI->output->set_output($this->render($view, $params));
138
	}
139
140
	/**
141
	 * Renders Twig Template and Returns as String
142
	 * 
143
	 * @param string $view   Template filename without `.twig`
144
	 * @param array  $params Array of parameters to pass to the template
145
	 * @return string
146
	 */
147
	public function render($view, $params = [])
148
	{
149
		$this->createTwig();
150
		// We call addFunctions() here, because we must call addFunctions()
151
		// after loading CodeIgniter functions in a controller.
152
		$this->addFunctions();
153
154
		$view = $view . '.twig';
155
		return $this->twig->render($view, $params);
156
	}
157
158
	protected function addFunctions()
159
	{
160
		// Runs only once
161
		if ($this->functions_added)
162
		{
163
			return;
164
		}
165
166
		// as is functions
167
		foreach ($this->functions_asis as $function)
168
		{
169
			if (function_exists($function))
170
			{
171
				$this->twig->addFunction(
172
					new \Twig_SimpleFunction(
173
						$function,
174
						$function
175
					)
176
				);
177
			}
178
		}
179
180
		// safe functions
181
		foreach ($this->functions_safe as $function)
182
		{
183
			if (function_exists($function))
184
			{
185
				$this->twig->addFunction(
186
					new \Twig_SimpleFunction(
187
						$function,
188
						$function,
189
						['is_safe' => ['html']]
190
					)
191
				);
192
			}
193
		}
194
195
		// customized functions
196
		if (function_exists('anchor'))
197
		{
198
			$this->twig->addFunction(
199
				new \Twig_SimpleFunction(
200
					'anchor',
201
					[$this, 'safe_anchor'],
202
					['is_safe' => ['html']]
203
				)
204
			);
205
		}
206
207
		$this->functions_added = TRUE;
208
	}
209
210
	/**
211
	 * @param string $uri
212
	 * @param string $title
213
	 * @param array  $attributes [changed] only array is acceptable
214
	 * @return string
215
	 */
216
	public function safe_anchor($uri = '', $title = '', $attributes = [])
217
	{
218
		$uri = html_escape($uri);
219
		$title = html_escape($title);
220
		
221
		$new_attr = [];
222
		foreach ($attributes as $key => $val)
223
		{
224
			$new_attr[html_escape($key)] = html_escape($val);
225
		}
226
227
		return anchor($uri, $title, $new_attr);
228
	}
229
230
	/**
231
	 * @return \Twig_Environment
232
	 */
233
	public function getTwig()
234
	{
235
		$this->createTwig();
236
		return $this->twig;
237
	}
238
}
239