Completed
Pull Request — master (#65)
by AD
09:37
created

TwigView::loadHelper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 2
cts 2
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 2
crap 1
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
        '.tpl',
45
        '.ctp',
46
    ];
47
48
    /**
49
     * Twig instance.
50
     *
51
     * @var \Twig\Environment
52
     */
53
    protected $twig;
54
55
    /**
56
     * Helpers.
57
     *
58
     * @var \Cake\View\Helper[]
59
     */
60
    protected $helperList = [];
61
62
    /**
63
     * Initialize view.
64
     *
65
     * @return void
66
     */
67
    public function initialize()
68
    {
69
        $this->twig = new Environment($this->getLoader(), $this->resolveConfig());
70
71
        $this->getEventManager()->dispatch(ConstructEvent::create($this, $this->twig));
72
73
        $this->_ext = self::EXT;
74
75
        parent::initialize();
76
    }
77
78
    /**
79
     * @param string $extension
80 9
     */
81
    public function unshiftExtension($extension)
82
    {
83
        array_unshift($this->extensions, $extension);
84
    }
85
86 9
    /**
87 8
     * Get twig environment instance.
88
     *
89 9
     * @return \Twig\Environment
90
     */
91 9
    public function getTwig(): Environment
92
    {
93 9
        return $this->twig;
94
    }
95 9
96 9
    /**
97
     * @return array
98 9
     */
99 9
    protected function resolveConfig(): array
100
    {
101
        $charset = 'utf-8';
102
        if (Configure::read('App.encoding') !== null) {
103
            $charset = strtolower(Configure::read('App.encoding'));
104
        }
105
        $debugFlag = false;
106
        if (Configure::read('App.encoding') === true) {
107
            $debugFlag = true;
108
        }
109
        $config = [
110
            'cache' => CACHE . 'twigView' . DS,
111
            'charset' => $charset,
112
            'auto_reload' => $debugFlag,
113
            'debug' => $debugFlag,
114 3
        ];
115
116 3
        $config = array_replace($config, $this->readConfig());
117
118
        $configEvent = EnvironmentConfigEvent::create($config);
119
        $this->getEventManager()->dispatch($configEvent);
120
121
        return $configEvent->getConfig();
122 9
    }
123
124 9
    /**
125 9
     * @return array
126
     */
127
    protected function readConfig(): array
128 9
    {
129 9
        if (!Configure::check(static::ENV_CONFIG)) {
130
            return [];
131
        }
132
133 9
        $config = Configure::read(static::ENV_CONFIG);
134 9
        if (!is_array($config)) {
135 9
            return [];
136 9
        }
137
138
        return $config;
139 9
    }
140
141 9
    /**
142 9
     * Create the template loader.
143
     *
144 9
     * @return \WyriHaximus\TwigView\Lib\Twig\Loader
145
     */
146
    protected function getLoader(): Loader
147
    {
148
        $event = LoaderEvent::create(new Loader());
149
        $this->getEventManager()->dispatch($event);
150 9
151
        return $event->getResultLoader();
152 9
    }
153 8
154
    /**
155
     * Load helper and add to list of helper instances.
156 1
     *
157 1
     * @param string $name Name of the helper to load.
158
     * @param array $config Settings for the helper
159
     * @return \Cake\View\Helper a constructed helper object.
160
     */
161 1
    public function loadHelper($name, array $config = [])
162
    {
163
        $helper = parent::loadHelper($name, $config);
164
165
        list(, $alias) = pluginSplit($name);
166
        $this->helperList[$alias] = $helper;
167
168
        return $helper;
169 9
    }
170
171 9
    /**
172 9
     * Render the template.
173
     *
174 9
     * @param string $viewFile Template file.
175
     * @param array  $data     Data that can be used by the template.
176
     *
177
     * @throws \Exception
178
     * @return string
179
     */
180
    protected function _render($viewFile, $data = []): string
181 9
    {
182
        if (empty($data)) {
183 9
            $data = $this->viewVars;
184
        }
185 9
186 9
        if (substr($viewFile, -3) === 'ctp') {
187 9
            $out = parent::_render($viewFile, $data);
188 3
        } else {
189 3
            $data = array_merge(
190
                $data,
191 9
                $this->helperList,
192
                [
193
                    '_view' => $this,
194
                ]
195
            );
196
197
            try {
198
                $out = $this->getTwig()->loadTemplate($viewFile)->render($data);
199
            } catch (Exception $e) {
200
                $previous = $e->getPrevious();
201
202 4
                if ($previous !== null && $previous instanceof Exception) {
203
                    throw $previous;
204 4
                } else {
205 4
                    throw $e;
206
                }
207
            }
208 4
        }
209 1
210
        return $out;
211 3
    }
212 3
213 3
    /**
214
     * @param  string|null $name
215 3
     * @throws \Exception
216
     * @return string
217
     */
218 View Code Duplication
    protected function _getViewFileName($name = null): string
219
    {
220 3
        $rethrow = new Exception('You\'re not supposed to get here');
221 2
        foreach ($this->extensions as $extension) {
222 2
            $this->_ext = $extension;
223
            try {
224 2
                return parent::_getViewFileName($name);
225 1
            } catch (Exception $exception) {
226
                $rethrow = $exception;
227 1
            }
228
        }
229
230
        throw $rethrow;
231
    }
232 2
233
    /**
234
     * @param  string|null $name
235
     * @throws \Exception
236
     * @return string
237
     */
238 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...
239
    {
240 2
        $rethrow = new Exception('You\'re not supposed to get here');
241
        foreach ($this->extensions as $extension) {
242 2
            $this->_ext = $extension;
243 2
            try {
244 2
                return parent::_getLayoutFileName($name);
245
            } catch (Exception $exception) {
246 2
                $rethrow = $exception;
247
            }
248
        }
249
250
        throw $rethrow;
251
    }
252
253
    /**
254
     * @param  string      $name
255
     * @param  bool        $pluginCheck
256
     * @return string|bool
257
     */
258
    protected function _getElementFileName($name, $pluginCheck = true)
259
    {
260
        foreach ($this->extensions as $extension) {
261
            $this->_ext = $extension;
262
            $result = parent::_getElementFileName($name, $pluginCheck);
263
            if ($result !== false) {
264
                return $result;
265
            }
266
        }
267
268
        return false;
269
    }
270
271
    /**
272
     * Return empty string when View instance is cast to string.
273
     *
274
     * @return string
275
     */
276
    public function __toString(): string
277
    {
278
        return '';
279
    }
280
}
281