Completed
Push — master ( b9e67a...92b65b )
by Cees-Jan
13s
created

TwigView::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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