Completed
Pull Request — master (#30)
by Cees-Jan
07:59 queued 05:48
created

TwigView   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 256
Duplicated Lines 11.72 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 64%

Importance

Changes 12
Bugs 3 Features 2
Metric Value
wmc 23
c 12
b 3
f 2
lcom 1
cbo 10
dl 30
loc 256
ccs 48
cts 75
cp 0.64
rs 10

11 Methods

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

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
        }
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
        ];
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 8
        $helpers = $registry->normalizeArray($this->helpers);
168 8
        foreach ($helpers as $properties) {
169 1
            list(, $class) = pluginSplit($properties['class']);
170 1
            $this->helperList[$class] = $this->{$class};
171
        }
172 8
    }
173
174
    /**
175
     * Render the template.
176
     *
177
     * @param string $viewFile Template file.
178
     * @param array  $data     Data that can be used by the template.
179
     *
180
     * @return string
181
     */
182
    // @codingStandardsIgnoreStart
183 2
    protected function _render($viewFile, $data = array())
184
    {
185
        // @codingStandardsIgnoreEnd
186 2
        if (empty($data)) {
187 2
            $data = $this->viewVars;
188
        }
189
190 2
        if (substr($viewFile, -3) === 'ctp') {
191 1
            $out = parent::_render($viewFile, $data);
192
            // @codingStandardsIgnoreStart
193
        } else {
194
            // @codingStandardsIgnoreEnd
195 1
            $data = array_merge(
196
                $data,
197 1
                $this->helperList,
198
                [
199 1
                    '_view' => $this,
200
                ]
201
            );
202
            // @codingStandardsIgnoreStart
203 1
            $out = $this->getTwig()->loadTemplate($viewFile)->render($data);
204
            // @codingStandardsIgnoreEnd
205
        }
206
207 2
        return $out;
208
    }
209
210
    /**
211
     * @param string|null $name
212
     * @return string
213
     * @throws \Exception
214
     */
215
    // @codingStandardsIgnoreStart
216 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...
217
    {
218
        // @codingStandardsIgnoreEnd
219
        $rethrow = new \Exception('You\'re not supposed to get here');
220
        foreach ($this->extensions as $extension) {
221
            $this->_ext = $extension;
222
            try {
223
                return parent::_getViewFileName($name);
224
            } catch (\Exception $exception) {
225
                $rethrow = $exception;
226
            }
227
        }
228
229
        throw $rethrow;
230
    }
231
232
    /**
233
     * @param string|null $name
234
     * @return string
235
     * @throws \Exception
236
     */
237
    // @codingStandardsIgnoreStart
238 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...
239
    {
240
        // @codingStandardsIgnoreEnd
241
        $rethrow = new \Exception('You\'re not supposed to get here');
242
        foreach ($this->extensions as $extension) {
243
            $this->_ext = $extension;
244
            try {
245
                return parent::_getLayoutFileName($name);
246
            } catch (\Exception $exception) {
247
                $rethrow = $exception;
248
            }
249
        }
250
251
        throw $rethrow;
252
    }
253
254
    /**
255
     * @param string $name
256
     * @return string
257
     * @throws \Exception
258
     */
259
    // @codingStandardsIgnoreStart
260
    protected function _getElementFileName($name)
261
    {
262
        // @codingStandardsIgnoreEnd
263
        foreach ($this->extensions as $extension) {
264
            $this->_ext = $extension;
265
            $result = parent::_getElementFileName($name);
266
            if ($result !== false) {
267
                return $result;
268
            }
269
        }
270
271
        return false;
272
    }
273
274
    /**
275
     * Get twig environment instance.
276
     *
277
     * @return \Twig_Environment
278
     */
279 1
    public function getTwig()
280
    {
281 1
        return $this->twig;
282
    }
283
}
284