TwigView::readConfig()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

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