Completed
Push — 1.0 ( 6ee45e...2aa723 )
by joanhey
02:40
created

Router::isRouted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 9
rs 9.6666
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    Router
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
 * Clase que Actua como router del Front-Controller
23
 *
24
 * Manejo de redirecciones de peticiones
25
 * Contiene información referente a la url de
26
 * la petición ( modudo, controlador, acción, parametros, etc )
27
 *
28
 * @category   Kumbia
29
 * @package    Router
30
 */
31
class Router {
32
    /**
33
     * Array estatico con las variables del router
34
     *
35
     * @var array
36
     */
37
38
    protected static $_vars = array(
39
        'method'          => null, //Método usado GET, POST, ...
40
        'route'           => null, //Ruta pasada en el GET
41
        'module'          => null, //Nombre del módulo actual
42
        'controller'      => 'index', //Nombre del controlador actual
43
        'action'          => 'index', //Nombre de la acción actual, por defecto index
44
        'parameters'      => array(), //Lista los parámetros adicionales de la URL
45
        'controller_path' => 'index',
46
        'default_path'    => APP_PATH, //Path donde se encuentran los controller
47
        'suffix'          => '_controller.php', //suffix for controler
48
        'dir'             => 'controllers', //dir of controller
49
    );
50
51
    /**
52
     * This is the name of router class
53
     * @var String
54
     */
55
    protected static $router = 'KumbiaRouter';
56
    //Es el router por defecto;
57
58
    /**
59
     * Indica si esta pendiente la ejecución de una ruta por parte del dispatcher
60
     *
61
     * @var boolean
62
     */
63
    protected static $_routed = false;
64
65
    /**
66
     * Procesamiento basico del router
67
     * @param string $url
68
     * @return void
69
     */
70
    public static function init($url) {
71
        // Se miran los parámetros por seguridad
72
        if (stripos($url, '/../') !== false) {
73
            throw new KumbiaException("Posible intento de hack en URL: '$url'");
74
        }
75
        // Si hay intento de hack TODO: añadir la ip y referer en el log
76
        self::$_vars['route'] = $url;
77
        //Método usado
78
        self::$_vars['method'] = $_SERVER['REQUEST_METHOD'];
79
    }
80
81
    /**
82
     * Ejecuta una url
83
     *
84
     * @param string $url
85
     * @return Controller
86
     */
87
    public static function execute($url) {
88
        self::init($url);
89
        //alias
90
        $router = self::$router;
91
        $conf   = Config::get('config.application.routes');
92
        //Si config.ini tiene routes activados, mira si esta routed
93
        if ($conf) {
94
            /*Esta activado el router*/
95
            /* This if for back compatibility*/
96
            if ($conf === '1') {
97
                $url = $router::_ifRouted($url);
98
            } else {
99
                /*Es otra clase de router*/
100
                $router = self::$router = $conf;
101
            }
102
        }
103
104
        // Descompone la url
105
        self::$_vars = $router::rewrite($url) + self::$_vars;
106
107
        // Despacha la ruta actual
108
        return self::dispatch( $router::getController(self::$_vars) );
109
    }
110
111
    /**
112
     * Realiza el dispatch de la ruta actual
113
     *
114
     * @return Controller
115
     */
116
    private static function dispatch($cont) {
117
        // Se ejecutan los filtros initialize y before
118
        if ($cont->k_callback(true) === false) {
119
            return $cont;
120
        }
121
122
        //Obteniendo el metodo
123
        try {
124
            $reflectionMethod = new ReflectionMethod($cont, $cont->action_name);
125
        } catch (ReflectionException $e) {
126
            throw new KumbiaException($cont->action_name, 'no_action');//TODO: enviar a un método del controller
127
        }
128
129
        //k_callback y __constructor metodo reservado
130
        if ($cont->action_name == 'k_callback' || $reflectionMethod->isConstructor()) {
131
            throw new KumbiaException('Esta intentando ejecutar un método reservado de KumbiaPHP');
132
        }
133
134
        //se verifica que los parametros que recibe
135
        //la action sea la cantidad correcta
136
        $num_params = count($cont->parameters);
137
        if ($cont->limit_params && ($num_params < $reflectionMethod->getNumberOfRequiredParameters() ||
138
                $num_params > $reflectionMethod->getNumberOfParameters())) {
139
            throw new KumbiaException(null, 'num_params');
140
        }
141
142
        try {
143
            $reflectionMethod->invokeArgs($cont, $cont->parameters);
144
        } catch (ReflectionException $e) {
145
            throw new KumbiaException(null, 'no_action');//TODO: mejor no_public
146
        }
147
148
        //Corre los filtros after y finalize
149
        $cont->k_callback();
150
151
        //Si esta routed internamente volver a ejecutar
152
        self::isRouted();
153
        
154
        return $cont;
155
    }
156
    
157
    /**
158
     * Redirecciona la ejecución internamente
159
     */
160
    protected static function isRouted() {
161
        
162
        if (self::$_routed) {
163
            self::$_routed = false;
164
            $router = self::$router;
165
            // Despacha la ruta actual
166
            self::dispatch( $router::getController(self::$_vars) );
167
        }
168
    }
169
    
170
    /**
171
     * Envia el valor de un atributo o el array con todos los atributos y sus valores del router
172
     * Mirar el atributo vars del router
173
     * ej.
174
     * <code>Router::get()</code>
175
     *
176
     * ej.
177
     * <code>Router::get('controller')</code>
178
     *
179
     * @param string $var (opcional) un atributo: route, module, controller, action, parameters o routed
180
     * @return array|string con el valor del atributo
181
     */
182
    public static function get($var = '') {
183
184
        return ($var) ? self::$_vars[$var] : self::$_vars;
185
    }
186
187
    /**
188
     * Redirecciona la ejecución internamente o externamente con un routes propio
189
     *
190
     * @param array $params array de $_vars (móddulo, controller, action, params, ...)
191
     * @param boolean $intern si la redirección es interna
192
     */
193
    public static function to($params, $intern = false) {
194
        if ($intern) {
195
            self::$_routed = true;
196
        }
197
198
        self::$_vars = $params + self::$_vars;
199
    }
200
}
201