-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwigView.php
117 lines (105 loc) · 2.6 KB
/
TwigView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
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
<?php
/**
* DframeFramework
* Copyright (c) Sławomir Kaleta.
*
* @license https://github.com/dframe/dframe/blob/master/LICENCE (MIT)
*/
namespace Dframe\View;
use Dframe\Config\Config;
use Dframe\View\Exceptions\ViewException;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
/**
* Twig View.
*
* @author Sławomir Kaleta <slaszka@gmail.com>
*/
class TwigView implements ViewInterface
{
/**
* @var Environment
*/
public $twig;
/**
* @var array
*/
public $assign;
/**
* TwigView constructor.
*/
public function __construct()
{
$twigConfig = Config::load('view/twig');
$loader = new FilesystemLoader($twigConfig->get('setTemplateDir'));
$twig = new Environment(
$loader,
[
'cache' => $twigConfig->get('setCompileDir'),
]
);
$this->twig = $twig;
}
/**
* Transfers the code to the twig template.
*
* @param string $name
* @param $value
*
* @return mixed
* @throws ViewException
*/
public function assign($name, $value)
{
if (isset($this->assign[$name])) {
throw new ViewException('You can\'t assign "' . $name . '" in Twig');
}
$assign = $this->assign[$name] = $value;
return $assign;
}
/**
* Return code.
*
* @param string $name
* @param string $path
*
* @return mixed
* @throws ViewException
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function fetch($name, $path = null)
{
return $this->renderInclude($name, $path);
}
/**
* Transfers the code to the Smarty template.
*
* @param string $name
* @param string $path
*
* @return mixed
* @throws ViewException
* @throws LoaderError
* @throws RuntimeError
* @throws SyntaxError
*/
public function renderInclude($name, $path = null)
{
$twigConfig = Config::load('twig');
$pathFile = pathFile($name);
$folder = $pathFile[0];
$name = $pathFile[1];
$path = $twigConfig->get('setTemplateDir') . DIRECTORY_SEPARATOR
. $folder . $name . $twigConfig->get('fileExtension', '.twig');
if (!is_file($path)) {
throw new ViewException('Can not open template ' . $name . ' in: ' . $path);
}
$renderInclude = $this->twig->render($name, $this->assign);
return $renderInclude;
}
}