Completed
Push — 1.0 ( f095f8...1b624d )
by joanhey
10s
created

KumbiaView::generate()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 47
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 20
c 1
b 0
f 0
nc 8
nop 1
dl 0
loc 47
rs 6.7272
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.txt.
9
 * It is also available through the world-wide-web at this URL:
10
 * http://wiki.kumbiaphp.com/Licencia
11
 * If you did not receive a copy of the license and are unable to
12
 * obtain it through the world-wide-web, please send an email
13
 * to [email protected] so we can send you a copy immediately.
14
 *
15
 * @category   Kumbia
16
 * @package    Core
17
 * @copyright  Copyright (c) 2005 - 2016 Kumbia Team (http://www.kumbiaphp.com)
18
 * @license    http://wiki.kumbiaphp.com/Licencia     New BSD License
19
 */
20
21
/**
22
 * Renderer de vistas
23
 *
24
 * @category   Kumbia
25
 * @package    Core
26
 */
27
class KumbiaView
28
{
29
30
    /**
31
     * Contenido
32
     *
33
     * @var string
34
     */
35
    protected static $_content;
36
    /**
37
     * Vista a renderizar
38
     *
39
     * @var string
40
     * */
41
    protected static $_view;
42
    /**
43
     * Template
44
     *
45
     * @var string
46
     */
47
    protected static $_template = 'default';
48
    /**
49
     * Indica el tipo de salida generada por el controlador
50
     *
51
     * @var string
52
     */
53
    protected static $_response;
54
    /**
55
     * Indica el path al que se le añadira la constante correspondiente
56
     *
57
     * @var string
58
     */
59
    protected static $_path;
60
    /**
61
     * Número de minutos que será cacheada la vista actual
62
     *
63
     * type: tipo de cache (view, template)
64
     * time: tiempo de vida de cache
65
     *
66
     * @var array
67
     */
68
    protected static $_cache = array('type' => FALSE, 'time' => FALSE, 'group' => FALSE);
69
70
    /**
71
     * Controlador actual
72
     *
73
     * @var Controller
74
     */
75
    protected static $_controller;
76
77
    /**
78
     * Cambia el view y opcionalmente el template
79
     *
80
     * @param string $view nombre del view a utilizar sin .phtml
81
     * @param string $template  opcional nombre del template a utilizar sin .phtml
82
     */
83
    public static function select($view, $template = FALSE)
84
    {
85
        self::$_view = $view;
86
87
        // verifica si se indico template
88
        if ($template !== FALSE) {
89
            self::$_template = $template;
90
        }
91
    }
92
93
    /**
94
     * Asigna el template para la vista
95
     *
96
     * @param string $template nombre del template a utilizar sin .phtml
97
     */
98
    public static function template($template)
99
    {
100
        self::$_template = $template;
101
    }
102
103
    /**
104
     * Indica el tipo de Respuesta dada por el controlador
105
     * buscando el view con esa extension.
106
     * ej. View::response('xml');
107
     * buscara: views/controller/action.xml.phtml
108
     *
109
     * @param string $response
110
     * @param string $template Opcional nombre del template sin .phtml
111
     */
112
    public static function response($response, $template = FALSE)
113
    {
114
        self::$_response = $response;
115
116
        // verifica si se indico template
117
        if ($template !== FALSE) {
118
            self::$_template = $template;
119
        }
120
    }
121
122
    /**
123
     * Asigna el path de la vista
124
     *
125
     * @param string $path path de la vista sin extension .phtml
126
     */
127
    public static function setPath($path)
128
    {
129
        self::$_path = $path . '/';
130
    }
131
132
    /**
133
     * Obtiene el path para vista incluyendo la extension .phtml
134
     *
135
     * @return string
136
     */
137
    public static function getPath()
138
    {
139
        if (self::$_response)
140
            return self::$_path . self::$_view . '.' . self::$_response . '.phtml';
141
142
        return self::$_path . self::$_view . '.phtml';
143
    }
144
145
    /**
146
     * Obtiene un atributo de KumbiaView
147
     *
148
     * @param string $atribute nombre de atributo (template, response, path, etc)
149
     */
150
    public static function get($atribute)
151
    {
152
        return self::${"_$atribute"};
153
    }
154
155
    /**
156
     * Asigna cacheo de vistas o template
157
     *
158
     * @param $time Tiempo de vida de cache
159
     * @param $type Tipo de cache (view, template)
160
     * @param $group Grupo de pertenencia de cache
161
     *
162
     * @return boolean  En producción y cache de view
163
     */
164
    public static function cache($time, $type='view', $group='kumbia.view')
165
    {
166
        if ($time === FALSE) { //TODO borrar cache
167
            self::$_cache['type'] = FALSE;
168
            return FALSE;
169
        }
170
        self::$_cache['type'] = $type;
171
        self::$_cache['time'] = $time;
172
        self::$_cache['group'] = $group;
173
        //Si está en producción para view
174
        if (PRODUCTION && $type === 'view') {
175
            return self::getCache(); //TRUE si está cacheada
176
        }
177
        return FALSE;
178
    }
179
180
    /**
181
     * Obtiene la cache de view
182
     *
183
     * @return boolean
184
     */
185
    protected static function getCache()
186
    {
187
        // el contenido permanece nulo si no hay nada cacheado o la cache expiro
188
        self::$_content = Cache::driver()->get(Router::get('route'), self::$_cache['group']);
189
        return self::$_content !== NULL;
190
    }
191
192
    /**
193
     * Obtiene el view
194
     *
195
     * @return string path del view
196
     */
197
    protected static function getView()
198
    {
199
        $file = APP_PATH . 'views/' . self::getPath();
200
        //Si no existe el view y es scaffold
201
        if (!is_file($file) && ($scaffold = self::$_controller->scaffold)) {
202
            $file = APP_PATH . "views/_shared/scaffolds/$scaffold/".self::$_view.'.phtml';
203
        }
204
        return $file;
205
    }
206
    /**
207
     * Cachea el view o template
208
     *
209
     * @param string $type view o template
210
     * @return void
211
     */
212
    protected static function saveCache($type)
213
    {
214
        // si esta en produccion y se cachea la vista
215
        if (PRODUCTION && self::$_cache['type'] === $type) {
216
                Cache::driver()->save(ob_get_contents(), self::$_cache['time'], Router::get('route'), self::$_cache['group']);
217
            }
218
    }
219
220
    /**
221
     * Renderiza la vista
222
     *
223
     * @param Controller $controller
224
     */
225
    public static function render(Controller $controller)
226
    {
227
        if (!self::$_view && !self::$_template)
228
            return ob_end_flush();
229
230
        // Guarda el controlador
231
        self::$_controller = $controller;
232
233
        self::generate($controller);
234
    }
235
236
    /**
237
     * Genera la vista
238
     *
239
     * @param Controller $controller
240
     */
241
    protected static function generate(Controller $controller)
242
    {
243
        // Registra la autocarga de helpers
244
        spl_autoload_register('kumbia_autoload_helper', true, true);
245
        // Mapea los atributos del controller en el scope
246
        extract(get_object_vars($controller), EXTR_OVERWRITE);
0 ignored issues
show
Bug introduced by
get_object_vars($controller) cannot be passed to extract() as the parameter $var_array expects a reference.
Loading history...
247
248
        // carga la vista si tiene view y no esta cacheada
249
        if (self::$_view && self::$_content === NULL) {
250
            // Carga el contenido del buffer de salida
251
            self::$_content = ob_get_clean();
252
            // Renderizar vista
253
            ob_start();
254
255
            // carga la vista
256
            if (!include self::getView())
257
                throw new KumbiaException('Vista "' . self::getPath() . '" no encontrada', 'no_view');
258
259
            // si esta en produccion y se cachea la vista
260
            self::saveCache('view');
261
262
            // Verifica si hay template
263
            if (!self::$_template) {
264
                ob_end_flush();
265
                return;
266
            }
267
268
            self::$_content = ob_get_clean();
269
270
        }
271
272
        // Renderizar template
273
        if ($__template = self::$_template) {
274
            ob_start();
275
276
            // carga el template
277
            if (!include APP_PATH . "views/_shared/templates/$__template.phtml")
278
                throw new KumbiaException("Template $__template no encontrado");
279
280
            // si esta en produccion y se cachea template
281
            self::saveCache('template');
282
283
            return ob_end_flush();
284
        }
285
286
        echo self::$_content;
287
    }
288
289
    /**
290
     * Imprime el contenido del buffer
291
     *
292
     */
293
    public static function content()
294
    {
295
        if (isset($_SESSION['KUMBIA.CONTENT'])) {
296
            echo $_SESSION['KUMBIA.CONTENT'];
297
            unset($_SESSION['KUMBIA.CONTENT']);
298
        }
299
        echo self::$_content;
300
    }
301
302
    /**
303
     * Renderiza una vista parcial
304
     *
305
     * @param string $partial vista a renderizar
306
     * @param string $__time tiempo de cache
307
     * @param array $params
308
     * @param string $group grupo de cache
309
     * @return string
310
     * @throw KumbiaException
311
     */
312
    public static function partial($partial, $__time='', $params=NULL, $group ='kumbia.partials')
313
    {
314
        if (PRODUCTION && $__time && !Cache::driver()->start($__time, $partial, $group)) {
315
            return;
316
        }
317
318
        //Verificando el partials en el dir app
319
        $__file = APP_PATH . "views/_shared/partials/$partial.phtml";
320
321
        if (!is_file($__file)) {
322
            //Verificando el partials en el dir core
323
            $__file = CORE_PATH . "views/partials/$partial.phtml";
324
        }
325
326
        if($params){
327
            if (is_string($params)) {
328
                    $params = Util::getParams(explode(',', $params));
329
            }
330
331
            // carga los parametros en el scope
332
            extract($params, EXTR_OVERWRITE);
333
        }
334
335
        // carga la vista parcial
336
        if (!include $__file) {
337
            throw new KumbiaException('Vista Parcial "' . $__file . '" no se encontro');
338
        }
339
340
        // se guarda en la cache de ser requerido
341
        if (PRODUCTION && $__time) {
342
            Cache::driver()->end();
343
        }
344
    }
345
346
    /**
347
     * Obtiene el valor de un atributo público o todos del controlador
348
     *
349
     * @param string $var nombre de variable
350
     * @return mixed valor de la variable
351
     */
352
    public static function getVar($var = '')
353
    {
354
        if(!$var) return get_object_vars(self::$_controller);
355
356
        return isset(self::$_controller->$var) ? self::$_controller->$var : NULL;
357
    }
358
}
359
360
/**
361
 * Atajo para htmlspecialchars, por defecto toma el charset de la
362
 * aplicacion
363
 *
364
 * @param string $s
365
 * @param string $charset
366
 * @return string
367
 */
368
function h($s, $charset = APP_CHARSET)
369
{
370
    return htmlspecialchars($s, ENT_QUOTES, $charset);
371
}