KumbiaRouter::rewrite()   B
last analyzed

Complexity

Conditions 7
Paths 14

Size

Total Lines 43
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 18
c 3
b 0
f 0
dl 0
loc 43
rs 8.8333
cc 7
nc 14
nop 1
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   Kumbia
11
 * @package    KumbiaRouter
12
 *
13
 * @copyright  Copyright (c) 2005 - 2023 KumbiaPHP Team (http://www.kumbiaphp.com)
14
 * @license    https://github.com/KumbiaPHP/KumbiaPHP/blob/master/LICENSE   New BSD License
15
 */
16
17
class KumbiaRouter
18
{
19
20
    /**
21
     * Toma $url y la descompone en (modulo), controlador, accion y argumentos
22
     *
23
     * @param string $url
24
     * @return  array
25
     */
26
    public static function rewrite(string $url): array
27
    {
28
        $router = [];
29
        //Valor por defecto
30
        if ($url === '/') {
31
            return $router;
32
        }
33
34
        //Se limpia la url, en caso de que la hallan escrito con el último parámetro sin valor, es decir controller/action/
35
        // Obtiene y asigna todos los parámetros de la url
36
        $urlItems = explode('/', trim($url, '/'));
37
38
        // El primer parámetro de la url es un módulo?
39
        if (is_dir(APP_PATH."controllers/$urlItems[0]")) {
40
            $router['module'] = $urlItems[0];
41
42
            // Si no hay más parámetros sale
43
            if (next($urlItems) === false) {
44
                $router['controller_path'] = "$urlItems[0]/index";
45
                return $router;
46
            }
47
        }
48
49
        // Controlador, cambia - por _
50
        $router['controller']      = str_replace('-', '_', current($urlItems));
51
        $router['controller_path'] = isset($router['module']) ? "$urlItems[0]/".$router['controller'] : $router['controller'];
52
53
        // Si no hay más parámetros sale
54
        if (next($urlItems) === false) {
55
            return $router;
56
        }
57
58
        // Acción
59
        $router['action'] = current($urlItems);
60
61
        // Si no hay más parámetros sale
62
        if (next($urlItems) === false) {
63
            return $router;
64
        }
65
66
        // Crea los parámetros y los pasa
67
        $router['parameters'] = array_slice($urlItems, key($urlItems));
0 ignored issues
show
Bug introduced by
It seems like key($urlItems) can also be of type null and string; however, parameter $offset of array_slice() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
        $router['parameters'] = array_slice($urlItems, /** @scrutinizer ignore-type */ key($urlItems));
Loading history...
68
        return $router;
69
    }
70
71
    /**
72
     * Busca en la tabla de entutamiento si hay una ruta en config/routes.ini
73
     * para el controlador, accion, id actual
74
     *
75
     * @param string $url Url para enrutar
76
     * @return string
77
     */
78
    public static function ifRouted(string $url): string
79
    {
80
        $routes = Config::get('routes.routes');
81
82
        // Si existe una ruta exacta la devuelve
83
        if (isset($routes[$url])) {
84
            return $routes[$url];
85
        }
86
87
        // Si existe una ruta con el comodín * crea la nueva ruta
88
        foreach ($routes as $key => $val) {
89
            if ($key === '/*') {
90
                return rtrim($val, '*').$url;
91
            }
92
93
            if (strripos($key, '*', -1)) {
94
                $key = rtrim($key, '*');
95
                if (strncmp($url, $key, strlen($key)) == 0) {
96
                    return str_replace($key, rtrim($val, '*'), $url);
97
                }
98
            }
99
        }
100
        return $url;
101
    }
102
103
    /**
104
     * Carga y devuelve una instancia del controllador
105
     * 
106
     * @throws KumbiaException
107
     * 
108
     * @return Controller
109
     */
110
    public static function getController(array $params): Controller
111
    {
112
        if (!include_once APP_PATH."controllers/{$params['controller_path']}_controller.php") {
113
            // Extrae las variables para manipularlas facilmente
114
            extract($params, EXTR_OVERWRITE);
115
            throw new KumbiaException('', 'no_controller');
116
        }
117
        //Asigna el controlador activo
118
        $controller = Util::camelcase($params['controller']).'Controller';
119
        return new $controller($params);
120
    }
121
}
122