Completed
Push — master ( e74ae2...768df3 )
by Cees-Jan
24s
created

TwigView::_getViewFileName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 7
cts 8
cp 0.875
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 3.0175
1
<?php declare(strict_types=1);
2
/**
3
 * This file is part of TwigView.
4
 *
5
 ** (c) 2014 Cees-Jan Kiewiet
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace WyriHaximus\TwigView\View;
12
13
use Cake\Core\Configure;
14
use Cake\View\View;
15
use Exception;
16
use Twig\Environment;
17
use WyriHaximus\TwigView\Event\ConstructEvent;
18
use WyriHaximus\TwigView\Event\EnvironmentConfigEvent;
19
use WyriHaximus\TwigView\Event\LoaderEvent;
20
use WyriHaximus\TwigView\Lib\Twig\Loader;
21
22
/**
23
 * Class TwigView.
24
 * @package WyriHaximus\TwigView\View
25
 */
26
class TwigView extends View
27
{
28
    const EXT = '.twig';
29
30
    const ENV_CONFIG = 'WyriHaximus.TwigView.environment';
31
32
    /**
33
     * Extension to use.
34
     *
35
     * @var string
36
     */
37
    protected $_ext = self::EXT;
38
39
    /**
40
     * @var array
41
     */
42
    protected $extensions = [
43
        self::EXT,
44
        '.php',
45
    ];
46
47
    /**
48
     * Twig instance.
49
     *
50
     * @var \Twig\Environment
51
     */
52
    protected $twig;
53
54
    /**
55
     * Return empty string when View instance is cast to string.
56
     *
57
     * @return string
58
     */
59
    public function __toString(): string
60
    {
61
        return '';
62
    }
63
64
    /**
65
     * Initialize view.
66
     *
67
     */
68 17
    public function initialize(): void
69
    {
70 17
        $this->twig = new Environment($this->getLoader(), $this->resolveConfig());
71
72 17
        $this->getEventManager()->dispatch(ConstructEvent::create($this, $this->twig));
73
74 17
        $this->_ext = self::EXT;
75
76 17
        parent::initialize();
77 17
    }
78
79
    /**
80
     * @param string $extension
81
     */
82
    public function unshiftExtension($extension)
83
    {
84
        array_unshift($this->extensions, $extension);
85
    }
86
87
    /**
88
     * Get twig environment instance.
89
     *
90
     * @return \Twig\Environment
91
     */
92 5
    public function getTwig(): Environment
93
    {
94 5
        return $this->twig;
95
    }
96
97
    /**
98
     * @internal
99
     */
100 4
    public function setTwig(Environment $twig): void
101
    {
102 4
        $this->twig = $twig;
103 4
    }
104
105
    /**
106
     * @return array
107
     */
108 17
    protected function resolveConfig(): array
109
    {
110 17
        $charset = 'utf-8';
111 17
        if (Configure::read('App.encoding') !== null) {
112
            $charset = strtolower(Configure::read('App.encoding'));
113
        }
114 17
        $debugFlag = false;
115 17
        if (Configure::read('App.encoding') === true) {
116
            $debugFlag = true;
117
        }
118
        $config = [
119 17
            'cache' => CACHE . 'twigView' . DS,
120 17
            'charset' => $charset,
121 17
            'auto_reload' => $debugFlag,
122 17
            'debug' => $debugFlag,
123
        ];
124
125 17
        $config = array_replace($config, $this->readConfig());
126
127 17
        $configEvent = EnvironmentConfigEvent::create($config);
128 17
        $this->getEventManager()->dispatch($configEvent);
129
130 17
        return $configEvent->getConfig();
131
    }
132
133
    /**
134
     * @return array
135
     */
136 17
    protected function readConfig(): array
137
    {
138 17
        if (!Configure::check(static::ENV_CONFIG)) {
139 16
            return [];
140
        }
141
142 1
        $config = Configure::read(static::ENV_CONFIG);
143 1
        if (!is_array($config)) {
144
            return [];
145
        }
146
147 1
        return $config;
148
    }
149
150
    /**
151
     * Create the template loader.
152
     *
153
     * @return \WyriHaximus\TwigView\Lib\Twig\Loader
154
     */
155 17
    protected function getLoader(): Loader
156
    {
157 17
        $event = LoaderEvent::create(new Loader());
158 17
        $this->getEventManager()->dispatch($event);
159
160 17
        return $event->getResultLoader();
161
    }
162
163
    /**
164
     * Render the template.
165
     *
166
     * @param string $viewFile Template file.
167
     * @param array  $data     Data that can be used by the template.
168
     *
169
     * @throws \Exception
170
     * @return string
171
     */
172 3
    protected function _render(string $viewFile, array $data = []): string
173
    {
174 3
        if (empty($data)) {
175 3
            $data = $this->viewVars;
176
        }
177
178 3
        if (substr($viewFile, -3) === 'php') {
179 1
            $out = parent::_render($viewFile, $data);
180
        } else {
181 2
            $data = array_merge(
182 2
                $data,
183 2
                iterator_to_array($this->helpers()->getIterator()),
184
                [
185 2
                    '_view' => $this,
186
                ]
187
            );
188
189
            try {
190 2
                $out = $this->getTwig()->loadTemplate($viewFile)->render($data);
191 2
            } catch (Exception $e) {
192 2
                $previous = $e->getPrevious();
193
194 2
                if ($previous !== null && $previous instanceof Exception) {
195 1
                    throw $previous;
196
                } else {
197 1
                    throw $e;
198
                }
199
            }
200
        }
201
202 1
        return $out;
203
    }
204
205
    /**
206
     * @param  string|null $name
207
     * @throws \Exception
208
     * @return string
209
     */
210 3
    protected function _getViewFileName(?string $name = null): string
211
    {
212 3
        $rethrow = new Exception('You\'re not supposed to get here');
213 3
        foreach ($this->extensions as $extension) {
214 3
            $this->_ext = $extension;
215
            try {
216 3
                return parent::_getViewFileName($name);
217 1
            } catch (Exception $exception) {
218 1
                $rethrow = $exception;
219
            }
220
        }
221
222
        throw $rethrow;
223
    }
224
225
    /**
226
     * @param  string|null $name
227
     * @throws \Exception
228
     * @return string
229
     */
230 1
    protected function _getLayoutFileName(?string $name = null): string
231
    {
232 1
        $rethrow = new Exception('You\'re not supposed to get here');
233 1
        foreach ($this->extensions as $extension) {
234 1
            $this->_ext = $extension;
235
            try {
236 1
                return parent::_getLayoutFileName($name);
237 1
            } catch (Exception $exception) {
238 1
                $rethrow = $exception;
239
            }
240
        }
241
242
        throw $rethrow;
243
    }
244
245
    /**
246
     * @param  string      $name
247
     * @param  bool        $pluginCheck
248
     * @return string|bool
249
     */
250
    protected function _getElementFileName(string $name, bool $pluginCheck = true)
251
    {
252
        foreach ($this->extensions as $extension) {
253
            $this->_ext = $extension;
254
            $result = parent::_getElementFileName($name, $pluginCheck);
255
            if ($result !== false) {
256
                return $result;
257
            }
258
        }
259
260
        return false;
261
    }
262
}
263