Completed
Pull Request — master (#65)
by AD
06:08
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
     * @param string $extension
74
     */
75
    public function unshiftExtension($extension)
76
    {
77
        array_unshift($this->extensions, $extension);
78
    }
79
80 9
    /**
81
     * Get twig environment instance.
82
     *
83
     * @return \Twig\Environment
84
     */
85
    public function getTwig(): Environment
86 9
    {
87 8
        return $this->twig;
88
    }
89 9
90
    /**
91 9
     * @return array
92
     */
93 9
    protected function resolveConfig(): array
94
    {
95 9
        $charset = 'utf-8';
96 9
        if (Configure::read('App.encoding') !== null) {
97
            $charset = strtolower(Configure::read('App.encoding'));
98 9
        }
99 9
        $debugFlag = false;
100
        if (Configure::read('App.encoding') === true) {
101
            $debugFlag = true;
102
        }
103
        $config = [
104
            'cache' => CACHE . 'twigView' . DS,
105
            'charset' => $charset,
106
            'auto_reload' => $debugFlag,
107
            'debug' => $debugFlag,
108
        ];
109
110
        $config = array_replace($config, $this->readConfig());
111
112
        $configEvent = EnvironmentConfigEvent::create($config);
113
        $this->getEventManager()->dispatch($configEvent);
114 3
115
        return $configEvent->getConfig();
116 3
    }
117
118
    /**
119
     * @return array
120
     */
121
    protected function readConfig(): array
122 9
    {
123
        if (!Configure::check(static::ENV_CONFIG)) {
124 9
            return [];
125 9
        }
126
127
        $config = Configure::read(static::ENV_CONFIG);
128 9
        if (!is_array($config)) {
129 9
            return [];
130
        }
131
132
        return $config;
133 9
    }
134 9
135 9
    /**
136 9
     * Create the template loader.
137
     *
138
     * @return \WyriHaximus\TwigView\Lib\Twig\Loader
139 9
     */
140
    protected function getLoader(): Loader
141 9
    {
142 9
        $event = LoaderEvent::create(new Loader());
143
        $this->getEventManager()->dispatch($event);
144 9
145
        return $event->getResultLoader();
146
    }
147
148
    /**
149
     * Render the template.
150 9
     *
151
     * @param string $viewFile Template file.
152 9
     * @param array  $data     Data that can be used by the template.
153 8
     *
154
     * @throws \Exception
155
     * @return string
156 1
     */
157 1
    protected function _render($viewFile, $data = []): string
158
    {
159
        if (empty($data)) {
160
            $data = $this->viewVars;
161 1
        }
162
163
        if (substr($viewFile, -3) === 'ctp') {
164
            $out = parent::_render($viewFile, $data);
165
        } else {
166
            $data = array_merge(
167
                $data,
168
                iterator_to_array($this->helpers()->getIterator()),
169 9
                [
170
                    '_view' => $this,
171 9
                ]
172 9
            );
173
174 9
            try {
175
                $out = $this->getTwig()->loadTemplate($viewFile)->render($data);
176
            } catch (Exception $e) {
177
                $previous = $e->getPrevious();
178
179
                if ($previous !== null && $previous instanceof Exception) {
180
                    throw $previous;
181 9
                } else {
182
                    throw $e;
183 9
                }
184
            }
185 9
        }
186 9
187 9
        return $out;
188 3
    }
189 3
190
    /**
191 9
     * @param  string|null $name
192
     * @throws \Exception
193
     * @return string
194
     */
195 View Code Duplication
    protected function _getViewFileName($name = null): string
196
    {
197
        $rethrow = new Exception('You\'re not supposed to get here');
198
        foreach ($this->extensions as $extension) {
199
            $this->_ext = $extension;
200
            try {
201
                return parent::_getViewFileName($name);
202 4
            } catch (Exception $exception) {
203
                $rethrow = $exception;
204 4
            }
205 4
        }
206
207
        throw $rethrow;
208 4
    }
209 1
210
    /**
211 3
     * @param  string|null $name
212 3
     * @throws \Exception
213 3
     * @return string
214
     */
215 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...
216
    {
217
        $rethrow = new Exception('You\'re not supposed to get here');
218
        foreach ($this->extensions as $extension) {
219
            $this->_ext = $extension;
220 3
            try {
221 2
                return parent::_getLayoutFileName($name);
222 2
            } catch (Exception $exception) {
223
                $rethrow = $exception;
224 2
            }
225 1
        }
226
227 1
        throw $rethrow;
228
    }
229
230
    /**
231
     * @param  string      $name
232 2
     * @param  bool        $pluginCheck
233
     * @return string|bool
234
     */
235
    protected function _getElementFileName($name, $pluginCheck = true)
236
    {
237
        foreach ($this->extensions as $extension) {
238
            $this->_ext = $extension;
239
            $result = parent::_getElementFileName($name, $pluginCheck);
240 2
            if ($result !== false) {
241
                return $result;
242 2
            }
243 2
        }
244 2
245
        return false;
246 2
    }
247
248
    /**
249
     * Return empty string when View instance is cast to string.
250
     *
251
     * @return string
252
     */
253
    public function __toString(): string
254
    {
255
        return '';
256
    }
257
}
258