1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace N98\Util\Console\Helper; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use N98\Magento\Application\Config; |
7
|
|
|
use N98\Util\Template\Twig; |
8
|
|
|
use RuntimeException; |
9
|
|
|
use Symfony\Component\Console\Helper\Helper; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Helper to render twig templates |
13
|
|
|
*/ |
14
|
|
|
class TwigHelper extends Helper |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var \N98\Util\Template\Twig |
18
|
|
|
*/ |
19
|
|
|
protected $twig; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param Config $config |
23
|
|
|
* @throws RuntimeException |
24
|
|
|
*/ |
25
|
|
|
public function __construct(Config $config) |
26
|
|
|
{ |
27
|
|
|
$baseDirs = $this->getBaseDirsFromConfig($config); |
28
|
|
|
|
29
|
|
|
try { |
30
|
|
|
$this->twig = new Twig($baseDirs); |
31
|
|
|
} catch (Exception $e) { |
32
|
|
|
throw new RuntimeException($e->getMessage(), 0, $e); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Renders a twig template file |
38
|
|
|
* |
39
|
|
|
* @param string $template |
40
|
|
|
* @param array $variables |
41
|
|
|
* @return mixed |
42
|
|
|
*/ |
43
|
|
|
public function render($template, $variables = array()) |
44
|
|
|
{ |
45
|
|
|
return $this->twig->render($template, $variables); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Renders a twig string |
50
|
|
|
* |
51
|
|
|
* @param $string |
52
|
|
|
* @param array $variables |
53
|
|
|
* |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
public function renderString($string, $variables = array()) |
57
|
|
|
{ |
58
|
|
|
return $this->twig->renderString($string, $variables); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @inheritdoc |
63
|
|
|
*/ |
64
|
|
|
public function getName() |
65
|
|
|
{ |
66
|
|
|
return 'twig'; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* @param Config $config |
71
|
|
|
* @return array |
72
|
|
|
*/ |
73
|
|
|
private function getBaseDirsFromConfig(Config $config) |
74
|
|
|
{ |
75
|
|
|
$baseDir = __DIR__ . '/../../../../..'; # root of project source tree |
76
|
|
|
|
77
|
|
|
$baseDirs = array(); |
78
|
|
|
|
79
|
|
|
$dirs = array_reverse($config->getConfig(array('twig', 'baseDirs'))); |
80
|
|
|
|
81
|
|
|
foreach ($dirs as $dir) { |
82
|
|
|
if (!is_string($dir)) { |
83
|
|
|
continue; |
84
|
|
|
} |
85
|
|
|
if (2 > strlen($dir)) { |
86
|
|
|
continue; |
87
|
|
|
} |
88
|
|
|
if ('./' === substr($dir, 0, 2)) { |
89
|
|
|
$dir = $baseDir . substr($dir, 1); |
90
|
|
|
} |
91
|
|
|
$baseDirs[] = $dir; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
return $baseDirs; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|