Completed
Push — improvement-quickstart ( f0774b...1b1fec )
by Cees-Jan
14:56 queued 11:53
created

TwigView::getTwig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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