Passed
Push — main ( 55ba40...d89a45 )
by Nelson
01:28
created

determine_function_to_call()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
function load_file($file, $extension, $base_dir, $classification, $parameters = null)
4
{
5
	if (isset($parameters) && is_array($parameters)) {
6
		extract($parameters);
7
	}
8
	if (file_exists($base_dir . $file . $extension)) {	
9
		require $base_dir . $file . $extension;
10
	} else {
11
		throw (new Exception("$classification <b>$file</b> no existe!"));	
12
	}
13
}
14
15
function load_lib($lib)
16
{
17
	load_file($lib, ".php", PIN_PATH . 'libs' . DS, "Librería");
18
}
19
20
function load_config($config)
21
{
22
	load_file($config, ".php", PIN_PATH . 'config' . DS, "Configuración");
23
}
24
25
26
function load_helper($helper)
27
{
28
	load_file($helper, ".php", PIN_PATH . 'helpers' . DS, "Helper");
29
}
30
31
function load_view($view, array $parameters = null)
32
{
33
	load_file($view, ".phtml", PIN_PATH . 'views' . DS, "Vista", $parameters);
34
}
35
36
function load_partial($partial, array $parameters = null)
37
{
38
	load_file($partial, ".phtml", PIN_PATH . 'partials'. DS , "Parcial", $parameters);		
39
}
40
41
function redirect_to($url)
42
{
43
	$url = PUBLIC_PATH . $url;
44
	header("Location: $url", true, 301);
45
}
46
47
//implementar autoloader para clases
48
//espera que las clases se definan en PascalCase y los archivos
49
//usen snake_case. Ejemplo class QueryBuilder, archivo query_builder.php
50
spl_autoload_register(function($className){
51
	$file_name = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $className));
52
	$file = PIN_PATH . 'libs' . DS . $file_name . '.php';
53
	if (file_exists($file)) {
54
		require_once $file;
55
		return;
56
	} else {
57
		throw new Exception("$className no existe en $file", 1);		
58
	}
59
});
60
61
62
set_error_handler('handle_error');
63
set_exception_handler('handle_exception');
64
65
function handle_error($level, $message, $file, $line)
66
{
67
    if (error_reporting() !== 0) {  
68
        throw new \ErrorException($message, 0, $level, $file, $line);
69
    }
70
}
71
72
function handle_exception($exception)
73
{
74
    $code = $exception->getCode();
75
    if ($code != 404) {
76
        $code = 500;
77
    }
78
    http_response_code($code);
79
80
    if (error_reporting() !== 0) {
81
        echo "<div style='padding: 40px;'>";
82
		echo "<h1>Fatal error</h1>";
83
        echo "<p>Uncaught exception: '" . get_class($exception) . "'</p>";
84
        echo "<p>Message: '" . $exception->getMessage() . "'</p>";
85
        echo "<p>Stack trace:<pre>" . $exception->getTraceAsString() . "</pre></p>";
86
        echo "<p>Thrown in '" . $exception->getFile() . "' on line " . $exception->getLine() . "</p>";
87
		echo "</div>";
88
    }
89
}
90
91
92
function load_page_from_url($url)
93
{
94
    // Validar entrada
95
    if (!is_string($url)) {
96
        throw new InvalidArgumentException('URL must be a string');
97
    }
98
99
    // Extraer componentes de la URL
100
    $components = array_values(array_filter(explode('/', $url)));
101
    
102
    // Determinar página y función
103
    $page = $components[0] ?? 'default';
104
    $function = $components[1] ?? 'index';
105
    $params = array_slice($components, 2);
106
    
107
    // Validar existencia de la página
108
    $page_path = PIN_PATH . 'pages' . DS . $page . '.php';
109
    if (!file_exists($page_path)) {
110
        throw new Exception("La página <b>$page</b> no existe!");
111
    }
112
    
113
    require $page_path;
114
    
115
    // Ejecutar inicializador si existe
116
    if (function_exists('page_initializer')) {
117
        page_initializer();
118
    }
119
    
120
    // Determinar la función a ejecutar
121
    $function_to_call = determine_function_to_call($function);
122
    
123
    if (empty($function_to_call)) {
124
        throw new Exception("La función <b>$function</b> no existe en la página <b>$page</b>!");
125
    }
126
    
127
    return call_user_func_array($function_to_call, $params);
128
}
129
130
/**
131
 * Determina qué función debe ser llamada basada en el nombre de la función
132
 * y el método de la petición
133
 */
134
function determine_function_to_call($function)
135
{
136
    if (function_exists($function)) {
137
        return $function;
138
    }
139
    
140
    $request_method = strtolower($_SERVER['REQUEST_METHOD']);
141
    if (function_exists($request_method)) {
142
        return $request_method;
143
    }
144
    
145
    return null;
146
}
147