KumbiaView::partial()   B
last analyzed

Complexity

Conditions 10
Paths 19

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
nc 19
nop 4
dl 0
loc 33
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * KumbiaPHP web & app Framework
4
 *
5
 * LICENSE
6
 *
7
 * This source file is subject to the new BSD license that is bundled
8
 * with this package in the file LICENSE.
9
 *
10
 * @category   View
11
 *
12
 * @copyright  Copyright (c) 2005 - 2019 KumbiaPHP Team (http://www.kumbiaphp.com)
13
 * @license    https://github.com/KumbiaPHP/KumbiaPHP/blob/master/LICENSE   New BSD License
14
 */
15
16
/**
17
 * Renderer de vistas.
18
 *
19
 * @category   View
20
 */
21
class KumbiaView
22
{
23
    /**
24
     * Contenido.
25
     *
26
     * @var string|null
27
     */
28
    protected static $_content;
29
    /**
30
     * Vista a renderizar.
31
     *
32
     * @var string
33
     * */
34
    protected static $_view;
35
    /**
36
     * Template.
37
     *
38
     * @var string|null
39
     */
40
    protected static $_template = 'default';
41
    /**
42
     * Indica el tipo de salida generada por el controlador.
43
     *
44
     * @var string
45
     */
46
    protected static $_response;
47
    /**
48
     * Indica el path al que se le añadira la constante correspondiente.
49
     *
50
     * @var string
51
     */
52
    protected static $_path;
53
    /**
54
     * Número de minutos que será cacheada la vista actual.
55
     *
56
     * type: tipo de cache (view, template)
57
     * time: tiempo de vida de cache
58
     *
59
     * @var array
60
     */
61
    protected static $_cache = array('type' => false, 'time' => false, 'group' => false);
62
63
    /**
64
     * Datos del Controlador actual.
65
     *
66
     * @var array
67
     */
68
    protected static $_controller;
69
70
    /**
71
     * Cambia el view y opcionalmente el template.
72
     *
73
     * @param string|null    $view     nombre del view a utilizar sin .phtml
74
     * @param string|null    $template opcional nombre del template a utilizar sin .phtml
75
     * 
76
     * @return void
77
     */
78
    public static function select($view, $template = '')
79
    {
80
        self::$_view = $view;
81
82
        // verifica si se indico template
83
        if ($template !== '') {
84
            self::$_template = $template;
85
        }
86
    }
87
88
    /**
89
     * Asigna el template para la vista.
90
     *
91
     * @param string|null $template nombre del template a utilizar sin .phtml
92
     * 
93
     * @return void
94
     */
95
    public static function template($template)
96
    {
97
        self::$_template = $template;
98
    }
99
100
    /**
101
     * Indica el tipo de Respuesta dada por el controlador
102
     * buscando el view con esa extension.
103
     * ej. View::response('xml');
104
     * buscara: views/controller/action.xml.phtml.
105
     *
106
     * @param string        $response
107
     * @param string|null   $template Opcional nombre del template sin .phtml
108
     * 
109
     * @return void
110
     */
111
    public static function response($response, $template = null)
112
    {
113
        self::$_response = $response;
114
115
        // verifica si se indico template
116
        if ($template !== null) {
117
            self::$_template = $template;
118
        }
119
    }
120
121
    /**
122
     * Asigna el path de la vista.
123
     *
124
     * @param string $path path de la vista sin extension .phtml
125
     * 
126
     * @return void
127
     */
128
    public static function setPath($path)
129
    {
130
        self::$_path = $path.'/';
131
    }
132
133
    /**
134
     * Obtiene el path para vista incluyendo la extension .phtml.
135
     *
136
     * @return string
137
     */
138
    public static function getPath()
139
    {
140
        if (self::$_response) {
141
            return self::$_path.self::$_view.'.'.self::$_response.'.phtml';
142
        }
143
144
        return self::$_path.self::$_view.'.phtml';
145
    }
146
147
    /**
148
     * Obtiene un atributo de KumbiaView.
149
     *
150
     * @param string $atribute nombre de atributo (template, response, path, etc)
151
     * 
152
     * @return mixed
153
     */
154
    public static function get($atribute)
155
    {
156
        return self::${"_$atribute"};
157
    }
158
159
    /**
160
     * Asigna cacheo de vistas o template.
161
     *
162
     * @param string|null  $time Tiempo de vida de cache
163
     * @param string        $type Tipo de cache (view, template)
164
     * @param string        $group Grupo de pertenencia de cache
165
     *
166
     * @return bool En producción y cache de view
167
     */
168
    public static function cache($time, $type = 'view', $group = 'kumbia.view')
169
    {
170
        if ($time === null) { //TODO borrar cache
171
            return self::$_cache['type'] = false;
172
        }
173
        self::$_cache['type'] = $type;
174
        self::$_cache['time'] = $time;
175
        self::$_cache['group'] = $group;
176
        //Si está en producción para view
177
        if (PRODUCTION && $type === 'view') {
178
            return self::getCache(); //TRUE si está cacheada
179
        }
180
181
        return false;
182
    }
183
184
    /**
185
     * Obtiene la cache de view.
186
     *
187
     * @return bool
188
     */
189
    protected static function getCache()
190
    {
191
        // el contenido permanece nulo si no hay nada cacheado o la cache expiro
192
        self::$_content = Cache::driver()->get(Router::get('route'), self::$_cache['group']);
0 ignored issues
show
Bug introduced by joanhey
It seems like \Router::get('route') targeting Router::get() can also be of type array; however, Cache::get() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
193
194
        return self::$_content !== null;
195
    }
196
197
    /**
198
     * Obtiene el view.
199
     *
200
     * @return string path del view
201
     */
202
    protected static function getView()
203
    {
204
        $file = APP_PATH.'views/'.self::getPath();
205
        //Si no existe el view y es scaffold
206
        if (!is_file($file) && ($scaffold = self::$_controller['scaffold'])) {
207
            $file = APP_PATH."views/_shared/scaffolds/$scaffold/".self::$_view.'.phtml';
208
        }
209
210
        return $file;
211
    }
212
213
    /**
214
     * Cachea el view o template.
215
     *
216
     * @param string $type view o template
217
     * 
218
     * @return void
219
     */
220
    protected static function saveCache($type)
221
    {
222
        // si esta en produccion y se cachea la vista
223
        if (PRODUCTION && self::$_cache['type'] === $type) {
224
            Cache::driver()->save(ob_get_contents(), self::$_cache['time'], Router::get('route'), self::$_cache['group']);
0 ignored issues
show
Bug introduced by joanhey
It seems like \Router::get('route') targeting Router::get() can also be of type array; however, Cache::save() does only seem to accept string|null, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
225
        }
226
    }
227
228
    /**
229
     * Renderiza la vista.
230
     *
231
     * @param Controller $controller
232
     * 
233
     * @return void
234
     */
235
    public static function render(Controller $controller)
236
    {
237
        if (!self::$_view && !self::$_template) {
0 ignored issues
show
Bug Best Practice introduced by joanhey
The expression self::$_template of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
238
            ob_end_flush();
239
240
            return; 
241
        }
242
243
        // Guarda los datos del controlador y los envia
244
        self::generate(self::$_controller = get_object_vars($controller));
245
    }
246
247
    /**
248
     * Genera la vista.
249
     *
250
     * @param array $controller
251
     * 
252
     * @return void
253
     */
254
    protected static function generate($controller)
255
    {
256
        // Registra la autocarga de helpers
257
        spl_autoload_register('kumbia_autoload_helper', true, true);
258
        // Mapea los atributos del controller en el scope
259
        extract($controller, EXTR_OVERWRITE);
260
261
        // carga la vista si tiene view y no esta cacheada
262
        if (self::$_view && self::$_content === null) {
263
            // Carga el contenido del buffer de salida
264
            self::$_content = ob_get_clean();
265
            // Renderizar vista
266
            ob_start();
267
268
            // carga la vista
269
            if (!include self::getView()) {
270
                throw new KumbiaException('Vista "'.self::getPath().'" no encontrada', 'no_view');
271
            }
272
273
            // si esta en produccion y se cachea la vista
274
            self::saveCache('view');
275
276
            // Verifica si hay template
277
            if (!self::$_template) {
0 ignored issues
show
Bug Best Practice introduced by joanhey
The expression self::$_template of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
278
                ob_end_flush();
279
280
                return;
281
            }
282
283
            self::$_content = ob_get_clean();
284
            ob_clean();
285
        }
286
287
        // Renderizar template
288
        if ($__template = self::$_template) {
289
            ob_start();
290
291
            // carga el template
292
            if (!include APP_PATH."views/_shared/templates/$__template.phtml") {
293
                throw new KumbiaException("Template $__template no encontrado");
294
            }
295
296
            // si esta en produccion y se cachea template
297
            self::saveCache('template');
298
            ob_end_flush();
299
300
            return;
301
        }
302
303
        echo self::$_content;
304
    }
305
306
    /**
307
     * Imprime el contenido del buffer.
308
     * 
309
     * @return void
310
     */
311
    public static function content()
312
    {
313
        if (isset($_SESSION['KUMBIA.CONTENT'])) {
314
            echo $_SESSION['KUMBIA.CONTENT'];
315
            unset($_SESSION['KUMBIA.CONTENT']);
316
        }
317
        echo self::$_content;
318
    }
319
320
    /**
321
     * Renderiza una vista parcial.
322
     *
323
     * @throw KumbiaException
324
     * @param  string            $partial vista a renderizar
325
     * @param  string            $__time  tiempo de cache
326
     * @param  array|string|null $params  variables para el partial
327
     * @param  string            $group   grupo de cache
328
     * @return void
329
     */
330
    public static function partial($partial, $__time = '', $params = null, $group = 'kumbia.partials')
331
    {
332
        if (PRODUCTION && $__time && !Cache::driver()->start($__time, $partial, $group)) {
333
            return;
334
        }
335
336
        //Verificando el partials en el dir app
337
        $__file = APP_PATH."views/_shared/partials/$partial.phtml";
338
339
        if (!is_file($__file)) {
340
            //Verificando el partials en el dir core
341
            $__file = CORE_PATH."views/partials/$partial.phtml";
342
        }
343
344
        if ($params) {
345
            if (is_string($params)) {
346
                $params = Util::getParams(explode(',', $params));
347
            }
348
349
            // carga los parametros en el scope
350
            extract($params, EXTR_OVERWRITE);
351
        }
352
353
        // carga la vista parcial
354
        if (!include $__file) {
355
            throw new KumbiaException('Vista Parcial "'.$__file.'" no encontrada', 'no_partial');
356
        }
357
358
        // se guarda en la cache de ser requerido
359
        if (PRODUCTION && $__time) {
360
            Cache::driver()->end();
361
        }
362
    }
363
364
    /**
365
     * Obtiene el valor de un atributo público o todos del controlador.
366
     *
367
     * @param string $var nombre de variable
368
     *
369
     * @return mixed valor de la variable
370
     */
371
    public static function getVar($var = '')
372
    {
373
        if (!$var) {
374
            return self::$_controller;
375
        }
376
377
        return isset(self::$_controller[$var]) ? self::$_controller[$var] : null;
378
    }
379
}
380
381
/**
382
 * Atajo para htmlspecialchars, por defecto toma el charset de la
383
 * aplicacion.
384
 *
385
 * @param string $string
386
 * @param string $charset
387
 *
388
 * @return string
389
 */
390
function h($string, $charset = APP_CHARSET)
391
{
392
    return htmlspecialchars($string, ENT_QUOTES, $charset);
393
}
394