Completed
Push — 4.x-fix-nodes ( 1f82a2 )
by Cees-Jan
02:03
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
2
3
/**
4
 * This file is part of TwigView.
5
 *
6
 ** (c) 2014 Cees-Jan Kiewiet
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace WyriHaximus\TwigView\View;
12
13
use Cake\Core\Configure;
14
use Cake\View\View;
15
use Exception;
16
use WyriHaximus\TwigView\Event\ConstructEvent;
17
use WyriHaximus\TwigView\Event\EnvironmentConfigEvent;
18
use WyriHaximus\TwigView\Event\LoaderEvent;
19
use WyriHaximus\TwigView\Lib\Twig\Loader;
20
21
/**
22
 * Class TwigView
23
 * @package WyriHaximus\TwigView\View
24
 */
25
// @codingStandardsIgnoreStart
26
class TwigView extends View
27
// @codingStandardsIgnoreEnd
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
    // @codingStandardsIgnoreStart
39
    protected $_ext = self::EXT;
40
    // @codingStandardsIgnoreEnd
41
42
    /**
43
     * @var array
44
     */
45
    protected $extensions = [
46
        self::EXT,
47
        '.tpl',
48
        '.ctp',
49
    ];
50
51
    /**
52
     * Twig instance.
53
     *
54
     * @var \Twig_Environment
55
     */
56
    protected $twig;
57
58
    /**
59
     * Initialize view.
60
     *
61
     * @return void
62
     */
63 10
    public function initialize()
64
    {
65 10
        $this->twig = new \Twig_Environment($this->getLoader(), $this->resolveConfig());
66
67 10
        $this->eventManager()->dispatch(ConstructEvent::create($this, $this->twig));
68
69 10
        $this->_ext = self::EXT;
70
71 10
        parent::initialize();
72 10
    }
73
74
    /**
75
     * @return array
76
     */
77 10
    protected function resolveConfig()
78
    {
79
        $config = [
80 10
            'cache' => CACHE . 'twigView' . DS,
81 10
            'charset' => strtolower(Configure::read('App.encoding')),
82 10
            'auto_reload' => Configure::read('debug'),
83 10
            'debug' => Configure::read('debug'),
84
        ];
85
86 10
        $config = array_replace($config, $this->readConfig());
87
88 10
        $configEvent = EnvironmentConfigEvent::create($config);
89 10
        $this->eventManager()->dispatch($configEvent);
90 10
        return $configEvent->getConfig();
91
    }
92
93
    /**
94
     * @return array
95
     */
96 10
    protected function readConfig()
97
    {
98 10
        if (!Configure::check(static::ENV_CONFIG)) {
99 9
            return [];
100
        }
101
102 1
        $config = Configure::read(static::ENV_CONFIG);
103 1
        if (!is_array($config)) {
104
            return [];
105
        }
106
107 1
        return $config;
108
    }
109
110
    /**
111
     * @param string $extension
112
     */
113
    public function unshiftExtension($extension)
114
    {
115
        array_unshift($this->extensions, $extension);
116
    }
117
118
    /**
119
     * Create the template loader.
120
     *
121
     * @return \Twig_LoaderInterface
122
     */
123 10
    protected function getLoader()
124
    {
125 10
        $event = LoaderEvent::create(new Loader());
126 10
        $this->eventManager()->dispatch($event);
127 10
        return $event->getResultLoader();
128
    }
129
130
    /**
131
     * Get helper list.
132
     *
133
     * @return \Cake\View\Helper[]
134
     */
135 4
    protected function generateHelperList()
136
    {
137 4
        $registry = $this->helpers();
138 4
        $helperList = [];
139
140 4
        foreach ($registry->loaded() as $alias) {
141 3
            $helperList[$alias] = $registry->get($alias);
142
        }
143
144 4
        return $helperList;
145
    }
146
    /**
147
     * Render the template.
148
     *
149
     * @param string $viewFile Template file.
150
     * @param array  $data     Data that can be used by the template.
151
     *
152
     * @throws \Exception
153
     * @return string
154
     */
155
    // @codingStandardsIgnoreStart
156 4
    protected function _render($viewFile, $data = array())
157
    {
158
        // @codingStandardsIgnoreEnd
159 4
        if (empty($data)) {
160 4
            $data = $this->viewVars;
161
        }
162
163 4
        if (substr($viewFile, -3) === 'ctp') {
164 1
            $out = parent::_render($viewFile, $data);
165
            // @codingStandardsIgnoreStart
166
        } else {
167
            // @codingStandardsIgnoreEnd
168 3
            $data = array_merge(
169 3
                $data,
170 3
                $this->generateHelperList(),
171
                [
172 3
                    '_view' => $this,
173
                ]
174
            );
175
176
            // @codingStandardsIgnoreStart
177
            try {
178 3
                $out = $this->getTwig()->loadTemplate($viewFile)->render($data);
179 2
            } catch (Exception $e) {
180 2
                $previous = $e->getPrevious();
181
182 2
                if ($previous !== null && $previous instanceof Exception) {
183 1
                    throw $previous;
184
                } else {
185 1
                    throw $e;
186
                }
187
            }
188
            // @codingStandardsIgnoreEnd
189
        }
190
191 2
        return $out;
192
    }
193
194
    /**
195
     * @param string|null $name
196
     * @return string
197
     * @throws \Exception
198
     */
199
    // @codingStandardsIgnoreStart
200 2 View Code Duplication
    protected function _getViewFileName($name = null)
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...
201
    {
202
        // @codingStandardsIgnoreEnd
203 2
        $rethrow = new \Exception('You\'re not supposed to get here');
204 2
        foreach ($this->extensions as $extension) {
205 2
            $this->_ext = $extension;
206
            try {
207 2
                return parent::_getViewFileName($name);
208
            } catch (\Exception $exception) {
209
                $rethrow = $exception;
210
            }
211
        }
212
213
        throw $rethrow;
214
    }
215
216
    /**
217
     * @param string|null $name
218
     * @return string
219
     * @throws \Exception
220
     */
221
    // @codingStandardsIgnoreStart
222 View Code Duplication
    protected function _getLayoutFileName($name = null)
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...
223
    {
224
        // @codingStandardsIgnoreEnd
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
242
     * @throws \Exception
243
     */
244
    // @codingStandardsIgnoreStart
245
    protected function _getElementFileName($name, $pluginCheck = true)
246
    {
247
        // @codingStandardsIgnoreEnd
248
        foreach ($this->extensions as $extension) {
249
            $this->_ext = $extension;
250
            $result = parent::_getElementFileName($name, $pluginCheck);
251
            if ($result !== false) {
252
                return $result;
253
            }
254
        }
255
256
        return false;
257
    }
258
259
    /**
260
     * Get twig environment instance.
261
     *
262
     * @return \Twig_Environment
263
     */
264 3
    public function getTwig()
265
    {
266 3
        return $this->twig;
267
    }
268
269
    /**
270
     * Return empty string when View instance is cast to string.
271
     *
272
     * @return string
273
     */
274
    public function __toString()
275
    {
276
        return '';
277
    }
278
}
279