Completed
Push — master ( cd03ca...b9e67a )
by Cees-Jan
06:42
created

TwigView::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
226
    {
227
        $rethrow = new Exception('You\'re not supposed to get here');
228
        foreach ($this->extensions as $extension) {
229
            $this->_ext = $extension;
230 3
            try {
231 2
                return parent::_getLayoutFileName($name);
232 2
            } catch (Exception $exception) {
233
                $rethrow = $exception;
234 2
            }
235 1
        }
236
237 1
        throw $rethrow;
238
    }
239
240
    /**
241
     * @param  string      $name
242 2
     * @param  bool        $pluginCheck
243
     * @return string|bool
244
     */
245
    protected function _getElementFileName($name, $pluginCheck = true)
246
    {
247
        foreach ($this->extensions as $extension) {
248
            $this->_ext = $extension;
249
            $result = parent::_getElementFileName($name, $pluginCheck);
250 2
            if ($result !== false) {
251
                return $result;
252 2
            }
253 2
        }
254 2
255
        return false;
256 2
    }
257
}
258