Completed
Push — 0.6 ( 4da698...d438e8 )
by Olivier
02:15
created

PHPEngine::render()   B

Complexity

Conditions 2
Paths 3

Size

Total Lines 27
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 3
nop 4
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\Render;
13
14
/**
15
 * Renders PHP templates.
16
 */
17
class PHPEngine implements Engine
18
{
19
	/**
20
	 * @inheritdoc
21
	 */
22
	public function __invoke($template_pathname, $thisArg, array $variables, array $options = [])
23
	{
24
		$f = \Closure::bind(function($__TEMPLATE_PATHNAME__, $__VARIABLES__) {
25
26
			unset($__VARIABLES__['this']);
27
28
			extract($__VARIABLES__);
29
30
			require $__TEMPLATE_PATHNAME__;
31
32
		}, $this->ensure_is_object($thisArg));
33
34
		ob_start();
35
36
		try
37
		{
38
			$f($template_pathname, [ self::VAR_TEMPLATE_PATHNAME => $template_pathname ] + $variables);
39
40
			return ob_get_clean();
41
		}
42
		catch (\Exception $e)
43
		{
44
			ob_end_clean();
45
46
			throw $e;
47
		}
48
	}
49
50
	/**
51
	 * Ensures that a value is an object.
52
	 *
53
	 * - `value` is an object, value is returned.
54
	 * - `value` is an array, an `ArrayObject` instance is returned.
55
	 * - Otherwise `value` is cast into a string and a {@link String} instance is returned.
56
	 *
57
	 * @param $value
58
	 *
59
	 * @return \ArrayObject|StringObject
60
	 */
61
	protected function ensure_is_object($value)
62
	{
63
		if (is_object($value))
64
		{
65
			return $value;
66
		}
67
68
		if (is_array($value))
69
		{
70
			return new \ArrayObject($value);
71
		}
72
73
		return new StringObject($value);
74
	}
75
}
76