Completed
Pull Request — master (#32)
by Yves
02:28
created

TwigView   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 258
Duplicated Lines 11.63 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 65.12%

Importance

Changes 13
Bugs 3 Features 2
Metric Value
wmc 23
c 13
b 3
f 2
lcom 1
cbo 10
dl 30
loc 258
ccs 56
cts 86
cp 0.6512
rs 10

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 20 2
A resolveConfig() 0 15 1
A readConfig() 0 13 3
A unshiftExtension() 0 4 1
A getLoader() 0 6 1
A generateHelperList() 0 11 2
B _render() 0 26 3
A _getViewFileName() 15 15 3
A _getLayoutFileName() 15 15 3
A _getElementFileName() 0 13 3
A getTwig() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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