Compare commits
40 Commits
9a1e5a2379
...
master
Author | SHA1 | Date | |
---|---|---|---|
b19e7d8789 | |||
4dfdb52519 | |||
b0891885f9 | |||
b282d5479f | |||
c9f467345b | |||
0f46848d15 | |||
b2cb8d6883 | |||
e9126e7cde | |||
7169d2cae3 | |||
66b2bc0d91 | |||
c8ab2aa2cc | |||
1e302a9ea7 | |||
d0d0d4dc76 | |||
595e9c1316 | |||
45abea5301 | |||
d441f001ec | |||
19da122e05 | |||
1a0164c8ed | |||
ad9f8ec67d | |||
31c5c63952 | |||
6aef212350 | |||
c600688725 | |||
3e27b1b7af | |||
73b7b8f72a | |||
7baad428ec | |||
3d2a607768 | |||
df424ffab5 | |||
daf7250882 | |||
05cd83fd10 | |||
6b470a181d | |||
7beb161d2b | |||
701caae7eb | |||
100bdfe006 | |||
f1b79fdbc0 | |||
406f9a10a1 | |||
cc3cb6be41 | |||
59fff2a586 | |||
cd1685d2e7 | |||
b85fb7e034 | |||
a10308a8f6 |
@ -1,4 +1,5 @@
|
||||
<?php
|
||||
|
||||
// Configuración de la base de datos
|
||||
define('DB_TYPE', 'mysql');
|
||||
define('DB_HOST', 'localhost');
|
||||
@ -11,4 +12,4 @@ define('SITE_URL', '');
|
||||
|
||||
// Configuración avanzada
|
||||
define('ROOT_DIR', __DIR__);
|
||||
define('ROOT_CORE', ROOT_DIR.'/src');
|
||||
define('ROOT_CORE', ROOT_DIR . '/src');
|
||||
|
11
index.php
11
index.php
@ -1,24 +1,23 @@
|
||||
<?php
|
||||
|
||||
require_once('config.php');
|
||||
|
||||
// Incluir clases
|
||||
spl_autoload_register(function ($className) {
|
||||
$fp = str_replace('\\','/',$className);
|
||||
$fp = str_replace('\\', '/', $className);
|
||||
$name = basename($fp);
|
||||
$dir = dirname($fp);
|
||||
$file = ROOT_CORE.'/'.$dir.'/'.$name.'.php';
|
||||
$file = ROOT_CORE . '/' . $dir . '/' . $name . '.php';
|
||||
if (file_exists($file)) {
|
||||
require_once $file;
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
// Incluir routers
|
||||
$routers = glob(ROOT_CORE.'/Routers/*.php');
|
||||
$routers = glob(ROOT_CORE . '/Routers/*.php');
|
||||
|
||||
foreach($routers as $file){
|
||||
foreach ($routers as $file) {
|
||||
require_once($file);
|
||||
}
|
||||
|
||||
\Libs\Router::apply();
|
||||
?>
|
||||
|
@ -1,4 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
use Exception;
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
/**
|
||||
* Database - DuckBrain
|
||||
*
|
||||
@ -8,38 +15,33 @@
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
class Database extends PDO
|
||||
{
|
||||
private static array $databases = [];
|
||||
|
||||
namespace Libs;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Exception;
|
||||
|
||||
class Database extends PDO {
|
||||
static private array $databases = [];
|
||||
|
||||
private function __construct() {}
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
|
||||
*
|
||||
* @return PDO
|
||||
*/
|
||||
static public function getInstance(
|
||||
public static function getInstance(
|
||||
string $type = 'mysql',
|
||||
string $host = 'localhost',
|
||||
string $name = '',
|
||||
string $user = '',
|
||||
string $pass = '',
|
||||
): PDO
|
||||
{
|
||||
$key = $type.'/'.$host.'/'.$name.'/'.$user;
|
||||
): PDO {
|
||||
$key = $type . '/' . $host . '/' . $name . '/' . $user;
|
||||
if (empty(static::$databases[$key])) {
|
||||
|
||||
if ($type == 'sqlite') {
|
||||
$dsn = $type .':'. $name;
|
||||
} else
|
||||
$dsn = $type.':dbname='.$name.';host='.$host;
|
||||
$dsn = $type . ':' . $name;
|
||||
} else {
|
||||
$dsn = $type . ':dbname=' . $name . ';host=' . $host;
|
||||
}
|
||||
|
||||
try {
|
||||
static::$databases[$key] = new PDO($dsn, $user, $pass);
|
||||
@ -55,4 +57,3 @@ class Database extends PDO {
|
||||
return static::$databases[$key];
|
||||
}
|
||||
}
|
||||
?>
|
||||
|
@ -1,4 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
/**
|
||||
* Middleware - DuckBrain
|
||||
*
|
||||
@ -8,11 +11,8 @@
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
|
||||
namespace Libs;
|
||||
|
||||
class Middleware {
|
||||
|
||||
class Middleware
|
||||
{
|
||||
/**
|
||||
* Llama al siguiente callback.
|
||||
*
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,27 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
use AllowDynamicProperties;
|
||||
|
||||
/**
|
||||
* Neuron - DuckBrain
|
||||
*
|
||||
* Neuron, sirve para crear un objeto que alojará valores, pero
|
||||
* además tiene la característica especial de que al intentar
|
||||
* acceder a un atributo que no está definido devolerá nulo en
|
||||
* lugar de generar un error php notice que indica que se está
|
||||
* intentando acceder a un valor no definido.
|
||||
* Neuron, sirve para crear un objeto que alojará valores.
|
||||
* Además, tiene la característica especial de que al intentar
|
||||
* acceder a una propiedad no definida, devolverá null en
|
||||
* lugar de generar un aviso (PHP notice) por variable o propiedad no definida.
|
||||
*
|
||||
* El constructor recibe un objeto o arreglo con los valores que
|
||||
* sí estarán definidos.
|
||||
* El constructor acepta un objeto o un arreglo que contiene los
|
||||
* valores que estarán definidos.
|
||||
*
|
||||
* @author KJ
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
|
||||
namespace Libs;
|
||||
use AllowDynamicProperties;
|
||||
|
||||
#[AllowDynamicProperties]
|
||||
class Neuron {
|
||||
|
||||
class Neuron
|
||||
{
|
||||
/**
|
||||
* __construct
|
||||
*
|
||||
@ -29,20 +29,24 @@ class Neuron {
|
||||
*/
|
||||
public function __construct(...$data)
|
||||
{
|
||||
if (count($data) === 1 &&
|
||||
if (
|
||||
count($data) === 1 &&
|
||||
isset($data[0]) &&
|
||||
(is_array($data[0]) ||
|
||||
is_object($data[0])))
|
||||
is_object($data[0]))
|
||||
) {
|
||||
$data = $data[0];
|
||||
}
|
||||
|
||||
foreach($data as $key => $value)
|
||||
foreach ($data as $key => $value) {
|
||||
$this->{$key} = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* __get
|
||||
*
|
||||
* @param string $index
|
||||
* @param string $index
|
||||
* @return null
|
||||
*/
|
||||
public function __get(string $index): null
|
||||
@ -50,5 +54,3 @@ class Neuron {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
@ -1,4 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
/**
|
||||
* Request - DuckBrain
|
||||
*
|
||||
@ -9,50 +12,151 @@
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
|
||||
namespace Libs;
|
||||
|
||||
class Request extends Neuron {
|
||||
/**
|
||||
* @var Neuron $get Objeto con todos los valores de $_GET.
|
||||
*/
|
||||
class Request extends Neuron
|
||||
{
|
||||
public Neuron $get;
|
||||
/**
|
||||
* @var Neuron $post Objeto con todos los valores de $_POST.
|
||||
*/
|
||||
public Neuron $post;
|
||||
/**
|
||||
* @var Neuron $json Objeto con todos los valores json enviados.
|
||||
*/
|
||||
public Neuron $put;
|
||||
public Neuron $patch;
|
||||
public Neuron $delete;
|
||||
public Neuron $json;
|
||||
/**
|
||||
* @var mixed $params Objeto con todos los valores pseudovariables de la uri.
|
||||
*/
|
||||
public Neuron $params;
|
||||
/**
|
||||
* @var mixed $path Ruta actual tomando como raíz la instalación de DuckBrain.
|
||||
*/
|
||||
public string $path;
|
||||
public string $error;
|
||||
public string $body;
|
||||
public array $next;
|
||||
|
||||
/**
|
||||
* __construct
|
||||
*
|
||||
* @param string $path Ruta actual tomando como raíz la instalación de DuckBrain.
|
||||
* @param string $path Ruta actual tomando como raíz la instalación de DuckBrain.
|
||||
*/
|
||||
public function __construct(string $path = '/')
|
||||
public function __construct()
|
||||
{
|
||||
$this->path = $path;
|
||||
$this->path = Router::currentPath();
|
||||
$this->get = new Neuron($_GET);
|
||||
$this->post = new Neuron($_POST);
|
||||
$this->put = new Neuron();
|
||||
$this->patch = new Neuron();
|
||||
$this->delete = new Neuron();
|
||||
$this->body = file_get_contents("php://input");
|
||||
|
||||
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
|
||||
if ($contentType === "application/json")
|
||||
if ($contentType === "application/json") {
|
||||
$this->json = new Neuron(
|
||||
(object) json_decode(trim(file_get_contents("php://input")), false)
|
||||
(object) json_decode(trim($this->body), false)
|
||||
);
|
||||
else
|
||||
$this->json = new Neuron();
|
||||
} else {
|
||||
$this->json = new Neuron();
|
||||
if (
|
||||
in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE']) &&
|
||||
preg_match('/^[^;?\/:@&=+$,]{1,255}[=]/', $this->body, $matches)
|
||||
) {
|
||||
// Con la expresión regular verificamos que sea un http
|
||||
// query string válido y evitamos errores de memoria en caso
|
||||
// de que el body tenga algo más grande que eso.
|
||||
parse_str($this->body, $input_vars);
|
||||
$this->{strtolower($_SERVER['REQUEST_METHOD'])} = new Neuron($input_vars);
|
||||
}
|
||||
}
|
||||
|
||||
$this->params = new Neuron();
|
||||
}
|
||||
|
||||
/**
|
||||
* Corre las validaciones e intenta continuar con la pila de callbacks.
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function handle(): mixed
|
||||
{
|
||||
if ($this->validate()) {
|
||||
return Middleware::next($this);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inicia la validación que se haya configurado.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function validate(): bool
|
||||
{
|
||||
$actual = match ($_SERVER['REQUEST_METHOD']) {
|
||||
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
|
||||
default => $this->get
|
||||
};
|
||||
|
||||
if (
|
||||
Validator::validateList(static::paramRules(), $this->params) &&
|
||||
Validator::validateList(static::getRules(), $this->get) &&
|
||||
Validator::validateList(static::rules(), $actual)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (isset(static::messages()[Validator::$lastFailed])) {
|
||||
$error = static::messages()[Validator::$lastFailed];
|
||||
} else {
|
||||
$error = 'Error: validation failed of ' . preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
|
||||
}
|
||||
|
||||
static::onInvalid($error);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reglas para el método actual.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reglas para los parámetros por URL.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function paramRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reglas para los parámetros GET.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getRules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mensajes de error en caso de fallar una validación.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Función a ejecutar cuando se ha detectado un valor no válido.
|
||||
*
|
||||
* @param string $error
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function onInvalid(string $error): void
|
||||
{
|
||||
http_response_code(422);
|
||||
print($error);
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
/**
|
||||
* Router - DuckBrain
|
||||
*
|
||||
@ -10,17 +13,15 @@
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
|
||||
namespace Libs;
|
||||
|
||||
class Router {
|
||||
class Router
|
||||
{
|
||||
private static $get = [];
|
||||
private static $post = [];
|
||||
private static $put = [];
|
||||
private static $patch = [];
|
||||
private static $delete = [];
|
||||
private static $last;
|
||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||
|
||||
/**
|
||||
* Función callback por defectio para cuando
|
||||
@ -28,7 +29,7 @@ class Router {
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function defaultNotFound (): void
|
||||
public static function defaultNotFound(): void
|
||||
{
|
||||
header("HTTP/1.0 404 Not Found");
|
||||
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
|
||||
@ -37,21 +38,23 @@ class Router {
|
||||
/**
|
||||
* __construct
|
||||
*/
|
||||
private function __construct() {}
|
||||
private function __construct()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsea para deectar las pseudovariables (ej: {variable})
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* Ruta con pseudovariables.
|
||||
*
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return array
|
||||
* Arreglo con 2 índices:
|
||||
* path - Contiene la ruta con las pseudovariables reeplazadas por expresiones regulares.
|
||||
* callback - Contiene el callback en formato Namespace\Clase::Método.
|
||||
* Arreglo con 2 índices:
|
||||
* path - Contiene la ruta con las pseudovariables reeplazadas por expresiones regulares.
|
||||
* callback - Contiene el callback en formato Namespace\Clase::Método.
|
||||
*/
|
||||
private static function parse(string $path, callable $callback): array
|
||||
{
|
||||
@ -62,12 +65,13 @@ class Router {
|
||||
$path = preg_replace(
|
||||
['/\\\{\w+\\\}/s'],
|
||||
['([^\/]+)'],
|
||||
$path);
|
||||
$path
|
||||
);
|
||||
|
||||
return [
|
||||
'path' => $path,
|
||||
'callback' => [$callback],
|
||||
'paramNames' => $paramNames
|
||||
'paramNames' => $paramNames,
|
||||
];
|
||||
}
|
||||
|
||||
@ -82,8 +86,9 @@ class Router {
|
||||
*/
|
||||
public static function basePath(): string
|
||||
{
|
||||
if (defined('SITE_URL') && !empty(SITE_URL))
|
||||
return parse_url(SITE_URL, PHP_URL_PATH);
|
||||
if (defined('SITE_URL') && !empty(SITE_URL)) {
|
||||
return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/') . '/';
|
||||
}
|
||||
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
|
||||
}
|
||||
|
||||
@ -91,7 +96,7 @@ class Router {
|
||||
* Redirije a una ruta relativa interna.
|
||||
*
|
||||
* @param string $path
|
||||
* La ruta relativa a la ruta base.
|
||||
* La ruta relativa a la ruta base.
|
||||
*
|
||||
* Ej: Si nuesto sistema está en "https://ejemplo.com/duckbrain"
|
||||
* llamamos a Router::redirect('/docs'), entonces seremos
|
||||
@ -100,7 +105,7 @@ class Router {
|
||||
*/
|
||||
public static function redirect(string $path): void
|
||||
{
|
||||
header('Location: '.static::basePath().substr($path,1));
|
||||
header('Location: ' . static::basePath() . ltrim($path, '/'));
|
||||
exit;
|
||||
}
|
||||
|
||||
@ -109,25 +114,27 @@ class Router {
|
||||
* Solo se puede usar un middleware a la vez.
|
||||
*
|
||||
* @param callable $callback
|
||||
* @param int $prioriry
|
||||
* @param int $prioriry
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Devuelve la instancia actual.
|
||||
*/
|
||||
public static function middleware(callable $callback, int $priority = null): static
|
||||
public static function middleware(callable $callback, ?int $priority = null): static
|
||||
{
|
||||
if (!isset(static::$last))
|
||||
if (!isset(static::$last)) {
|
||||
return new static();
|
||||
}
|
||||
|
||||
$method = static::$last[0];
|
||||
$index = static::$last[1];
|
||||
|
||||
if (isset($priority) && $priority <= 0)
|
||||
if (isset($priority) && $priority <= 0) {
|
||||
$priority = 1;
|
||||
}
|
||||
|
||||
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback']))
|
||||
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback'])) {
|
||||
static::$$method[$index]['callback'][] = $callback;
|
||||
else {
|
||||
} else {
|
||||
static::$$method[$index]['callback'] = array_merge(
|
||||
array_slice(static::$$method[$index]['callback'], 0, $priority),
|
||||
[$callback],
|
||||
@ -147,8 +154,9 @@ class Router {
|
||||
*/
|
||||
public static function reconfigure(callable $callback): static
|
||||
{
|
||||
if (empty(static::$last))
|
||||
if (empty(static::$last)) {
|
||||
return new static();
|
||||
}
|
||||
|
||||
$method = static::$last[0];
|
||||
$index = static::$last[1];
|
||||
@ -165,10 +173,10 @@ class Router {
|
||||
* solo configura la ruta como la última configurada
|
||||
* siempre y cuando la misma haya sido configurada previamente.
|
||||
*
|
||||
* @param string $method
|
||||
* Método http.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param string $method
|
||||
* Método http.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable|null $callback
|
||||
*
|
||||
* @return
|
||||
@ -181,34 +189,36 @@ class Router {
|
||||
$path = preg_replace(
|
||||
['/\\\{\w+\\\}/s'],
|
||||
['([^\/]+)'],
|
||||
$path);
|
||||
$path
|
||||
);
|
||||
|
||||
foreach(static::$$method as $index => $router)
|
||||
foreach (static::$$method as $index => $router) {
|
||||
if ($router['path'] == $path) {
|
||||
static::$last = [$method, $index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return new static();
|
||||
}
|
||||
|
||||
static::$$method[] = static::parse($path, $callback);
|
||||
static::$last = [$method, count(static::$$method)-1];
|
||||
static::$last = [$method, count(static::$$method) - 1];
|
||||
return new static();
|
||||
}
|
||||
|
||||
/**
|
||||
* Define los routers para el método GET.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Devuelve la instancia actual.
|
||||
*/
|
||||
public static function get(string $path, callable $callback = null): static
|
||||
public static function get(string $path, ?callable $callback = null): static
|
||||
{
|
||||
return static::configure('get', $path, $callback);
|
||||
}
|
||||
@ -216,15 +226,15 @@ class Router {
|
||||
/**
|
||||
* Define los routers para el método POST.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual.
|
||||
* Devuelve la instancia actual.
|
||||
*/
|
||||
public static function post(string $path, callable $callback = null): static
|
||||
public static function post(string $path, ?callable $callback = null): static
|
||||
{
|
||||
return static::configure('post', $path, $callback);
|
||||
}
|
||||
@ -232,16 +242,16 @@ class Router {
|
||||
/**
|
||||
* Define los routers para el método PUT.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Devuelve la instancia actual
|
||||
*/
|
||||
|
||||
public static function put(string $path, callable $callback = null): static
|
||||
public static function put(string $path, ?callable $callback = null): static
|
||||
{
|
||||
return static::configure('put', $path, $callback);
|
||||
}
|
||||
@ -249,15 +259,15 @@ class Router {
|
||||
/**
|
||||
* Define los routers para el método PATCH.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables.
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Devuelve la instancia actual
|
||||
*/
|
||||
public static function patch(string $path, callable $callback = null): static
|
||||
public static function patch(string $path, ?callable $callback = null): static
|
||||
{
|
||||
return static::configure('patch', $path, $callback);
|
||||
}
|
||||
@ -265,15 +275,15 @@ class Router {
|
||||
/**
|
||||
* Define los routers para el método DELETE.
|
||||
*
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables
|
||||
* @param callable $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
* @param string $path
|
||||
* Ruta con pseudovariables
|
||||
* @param callable|null $callback
|
||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||
*
|
||||
* @return static
|
||||
* Devuelve la instancia actual
|
||||
* Devuelve la instancia actual
|
||||
*/
|
||||
public static function delete(string $path, callable $callback = null): static
|
||||
public static function delete(string $path, ?callable $callback = null): static
|
||||
{
|
||||
return static::configure('delete', $path, $callback);
|
||||
}
|
||||
@ -283,36 +293,27 @@ class Router {
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function currentPath() : string
|
||||
public static function currentPath(): string
|
||||
{
|
||||
return preg_replace('/'.preg_quote(static::basePath(), '/').'/',
|
||||
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1);
|
||||
return preg_replace(
|
||||
'/' . preg_quote(static::basePath(), '/') . '/',
|
||||
'/',
|
||||
strtok($_SERVER['REQUEST_URI'], '?'),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aplica los routers.
|
||||
* Aplica la configuración de rutas.
|
||||
*
|
||||
* Este método ha de ser llamado luego de que todos los routers hayan sido configurados.
|
||||
* @param string|null $path (opcional) Ruta a usar. Si no se define, detecta la ruta actual.
|
||||
*
|
||||
* En caso que la ruta actual coincida con un router configurado, se comprueba si hay middleware; Si hay
|
||||
* middleware, se enviará el callback y los datos de la petición como un Neuron. Caso contrario, se enviarán
|
||||
* los datos directamente al callback.
|
||||
*
|
||||
* Con middleware:
|
||||
* $middleware($callback, $req)
|
||||
*
|
||||
* Sin middleware:
|
||||
* $callback($req)
|
||||
*
|
||||
* $req es una instancia de Neuron que tiene los datos de la petición.
|
||||
*
|
||||
* Si no la ruta no coincide con ninguna de las rutas configuradas, ejecutará el callback $notFoundCallback
|
||||
* @return void
|
||||
*/
|
||||
public static function apply(): void
|
||||
public static function apply(?string $path = null): void
|
||||
{
|
||||
$path = static::currentPath();
|
||||
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers configurados
|
||||
$path = $path ?? static::currentPath();
|
||||
$routers = match ($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
|
||||
'POST' => static::$post,
|
||||
'PUT' => static::$put,
|
||||
'PATCH' => static::$patch,
|
||||
@ -320,25 +321,61 @@ class Router {
|
||||
default => static::$get
|
||||
};
|
||||
|
||||
$req = new Request(static::currentPath());
|
||||
|
||||
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual
|
||||
if (preg_match_all('/^'.$router['path'].'\/?$/si',$path, $matches, PREG_PATTERN_ORDER)) {
|
||||
if (preg_match_all('/^' . $router['path'] . '\/?$/si', $path, $matches, PREG_PATTERN_ORDER)) {
|
||||
unset($matches[0]);
|
||||
|
||||
// Comprobando pseudo variables en la ruta
|
||||
if (isset($matches[1])) {
|
||||
foreach ($matches as $index => $match) {
|
||||
$paramName = $router['paramNames'][$index-1];
|
||||
$req->params->$paramName = urldecode($match[0]);
|
||||
// Objtener un reflection del callback
|
||||
$lastCallback = $router['callback'][0];
|
||||
if ($lastCallback instanceof \Closure) { // si es función anónima
|
||||
$reflectionCallback = new \ReflectionFunction($lastCallback);
|
||||
} else {
|
||||
if (is_string($lastCallback)) {
|
||||
$lastCallback = preg_split('/::/', $lastCallback);
|
||||
}
|
||||
|
||||
// Revisamos su es un método o solo una función
|
||||
if (count($lastCallback) == 2) {
|
||||
$reflectionCallback = new \ReflectionMethod($lastCallback[0], $lastCallback[1]);
|
||||
} else {
|
||||
$reflectionCallback = new \ReflectionFunction($lastCallback[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// Llamar al último callback configurado
|
||||
$next = array_pop($router['callback']);
|
||||
$req->next = $router['callback'];
|
||||
$data = call_user_func_array($next, [$req]);
|
||||
// Obtener los parámetros
|
||||
$arguments = $reflectionCallback->getParameters();
|
||||
if (isset($arguments[0])) {
|
||||
// Obtenemos la clase del primer parámetro
|
||||
$argumentClass = strval($arguments[0]->getType());
|
||||
|
||||
// Verificamos si la clase está o no tipada
|
||||
if (empty($argumentClass)) {
|
||||
$request = new Request();
|
||||
} else {
|
||||
$request = new $argumentClass();
|
||||
|
||||
// Verificamos que sea instancia de Request (requerimiento)
|
||||
if (!($request instanceof Request)) {
|
||||
throw new \Exception('Bad argument type on router callback.');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
$request = new Request();
|
||||
}
|
||||
|
||||
// Comprobando y guardando los parámetros variables de la ruta
|
||||
if (isset($matches[1])) {
|
||||
foreach ($matches as $index => $match) {
|
||||
$paramName = $router['paramNames'][$index - 1];
|
||||
$request->params->$paramName = urldecode($match[0]);
|
||||
}
|
||||
}
|
||||
|
||||
// Llama a la validación y luego procesa la cola de callbacks
|
||||
$request->next = $router['callback'];
|
||||
$data = $request->handle();
|
||||
|
||||
// Por defecto imprime como JSON si se retorna algo
|
||||
if (isset($data)) {
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($data));
|
||||
@ -349,7 +386,6 @@ class Router {
|
||||
}
|
||||
|
||||
// Si no hay router que coincida llamamos a $notFoundCallBack
|
||||
call_user_func_array(static::$notFoundCallback, [$req]);
|
||||
call_user_func_array(static::$notFoundCallback, [new Request()]);
|
||||
}
|
||||
}
|
||||
?>
|
||||
|
204
src/Libs/Validator.php
Normal file
204
src/Libs/Validator.php
Normal file
@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
/**
|
||||
* Validator - DuckBrain
|
||||
*
|
||||
* Libería complementaria de la libería Request.
|
||||
* Sirve para simplpificar la verificación de valores.
|
||||
*
|
||||
* Tiene la posibilida de verificar tanto reglas individuales como en lote.
|
||||
*
|
||||
* |----------+--------------------------------------------------------|
|
||||
* | Regla | Descripción |
|
||||
* |----------+--------------------------------------------------------|
|
||||
* | not | Niega la siguiente regla. Ej: not:float |
|
||||
* | exists | Es requerido; debe estar definido y puede estar vacío |
|
||||
* | required | Es requerido; debe estar definido y no vacío |
|
||||
* | number | Es numérico |
|
||||
* | int | Es entero |
|
||||
* | float | Es un float |
|
||||
* | bool | Es booleano |
|
||||
* | email | Es un correo |
|
||||
* | enum | Esta en un lista ve valores. Ej: enum:admin,user,guest |
|
||||
* | url | Es una url válida |
|
||||
* |----------+--------------------------------------------------------|
|
||||
*
|
||||
* Las listas de reglas están separadas por |, Ej: required|email
|
||||
*
|
||||
* @author KJ
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
class Validator
|
||||
{
|
||||
public static string $lastFailed = '';
|
||||
|
||||
/**
|
||||
* Validar lista de reglas sobre las propiedades de un objeto.
|
||||
*
|
||||
* @param array $rulesList Lista de reglas.
|
||||
* @param Neuron $haystack Objeto al que se le verificarán las reglas.
|
||||
*
|
||||
* @return bool Retorna true solo si todas las reglas se cumplen y false en cuanto una falle.
|
||||
*/
|
||||
public static function validateList(array $rulesList, Neuron $haystack): bool
|
||||
{
|
||||
foreach ($rulesList as $target => $rules) {
|
||||
$rules = preg_split('/\|/', $rules);
|
||||
foreach ($rules as $rule) {
|
||||
if (static::checkRule($haystack->{$target}, $rule)) {
|
||||
continue;
|
||||
}
|
||||
static::$lastFailed = $target . '.' . $rule;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revisa si una regla se cumple.
|
||||
*
|
||||
* @param mixed $subject Lo que se va a verfificar.
|
||||
* @param string $rule La regla a probar.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function checkRule(mixed $subject, string $rule): bool
|
||||
{
|
||||
$arguments = preg_split('/[:,]/', $rule);
|
||||
$rule = [static::class, $arguments[0]];
|
||||
$arguments[0] = $subject;
|
||||
|
||||
if (is_callable($rule)) {
|
||||
return call_user_func_array($rule, $arguments);
|
||||
}
|
||||
|
||||
throw new \Exception('Bad rule: "' . preg_split('/::/', $rule)[1] . '"');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifica la regla de manera negativa.
|
||||
*
|
||||
* @param mixed $subject Lo que se va a verfificar.
|
||||
* @param mixed $rule La regla a probar.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function not(mixed $subject, ...$rule): bool
|
||||
{
|
||||
return !static::checkRule($subject, join(':', $rule));
|
||||
}
|
||||
|
||||
/**
|
||||
* Comprueba que que esté definido/exista.
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function exists(mixed $subject): bool
|
||||
{
|
||||
return isset($subject);
|
||||
}
|
||||
|
||||
/**
|
||||
* Comprueba que que esté definido y no esté vacío.
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function required(mixed $subject): bool
|
||||
{
|
||||
return isset($subject) && !empty($subject);
|
||||
}
|
||||
|
||||
/**
|
||||
* number
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function number(mixed $subject): bool
|
||||
{
|
||||
return is_numeric($subject);
|
||||
}
|
||||
|
||||
/**
|
||||
* int
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function int(mixed $subject): bool
|
||||
{
|
||||
return filter_var($subject, FILTER_VALIDATE_INT);
|
||||
}
|
||||
|
||||
/**
|
||||
* float
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function float(mixed $subject): bool
|
||||
{
|
||||
return filter_var($subject, FILTER_VALIDATE_FLOAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* bool
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function bool(mixed $subject): bool
|
||||
{
|
||||
return filter_var($subject, FILTER_VALIDATE_BOOLEAN);
|
||||
}
|
||||
|
||||
/**
|
||||
* email
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function email(mixed $subject): bool
|
||||
{
|
||||
return filter_var($subject, FILTER_VALIDATE_EMAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* url
|
||||
*
|
||||
* @param mixed $subject
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function url(mixed $subject): bool
|
||||
{
|
||||
return filter_var($subject, FILTER_VALIDATE_URL);
|
||||
}
|
||||
|
||||
/**
|
||||
* enum
|
||||
*
|
||||
* @param mixed $subject
|
||||
* @param mixed $values
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public static function enum(mixed $subject, ...$values): bool
|
||||
{
|
||||
return in_array($subject, $values);
|
||||
}
|
||||
}
|
@ -1,4 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Libs;
|
||||
|
||||
/**
|
||||
* View - DuckBrain
|
||||
*
|
||||
@ -7,74 +10,71 @@
|
||||
* @author KJ
|
||||
* @website https://kj2.me
|
||||
* @licence MIT
|
||||
*/
|
||||
|
||||
namespace Libs;
|
||||
|
||||
class View extends Neuron {
|
||||
|
||||
*/
|
||||
class View extends Neuron
|
||||
{
|
||||
/**
|
||||
* Incluye el archivo.
|
||||
*
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
||||
* @param string $viewPath (opcional) Ruta donde se encuentra la vista.
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
||||
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista.
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function include(
|
||||
protected function include(
|
||||
string $viewName,
|
||||
string $viewPath = null,
|
||||
?string $viewPath = null,
|
||||
string $extension = 'php'
|
||||
): void
|
||||
{
|
||||
$view = $this;
|
||||
|
||||
if (isset($viewPath) &&
|
||||
file_exists("$viewPath$viewName.$extension")) {
|
||||
): void {
|
||||
if (
|
||||
isset($viewPath) &&
|
||||
file_exists("$viewPath$viewName.$extension")
|
||||
) {
|
||||
include("$viewPath$viewName.$extension");
|
||||
return;
|
||||
}
|
||||
|
||||
include(ROOT_CORE."/Views/$viewName.$extension");
|
||||
include(ROOT_CORE . "/Views/$viewName.$extension");
|
||||
}
|
||||
|
||||
/**
|
||||
* Función que "renderiza" las vistas
|
||||
*
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
||||
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista mediante $view ($param['index'] se usaría así: $view->index)
|
||||
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
||||
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista
|
||||
* mediante $view ($param['index'] se usaría así: $view->index)
|
||||
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que
|
||||
* la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function render(
|
||||
string $viewName,
|
||||
array|Neuron $params = [],
|
||||
string $viewPath = null,
|
||||
string $extension = 'php'
|
||||
): void
|
||||
{
|
||||
?string $viewPath = null,
|
||||
string $extension = 'php'
|
||||
): void {
|
||||
$instance = new View($params);
|
||||
$instance->html($viewName, $viewPath);
|
||||
$instance->html($viewName, $viewPath, $extension);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderiza las vistas HTML
|
||||
*
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
|
||||
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function html(
|
||||
string $viewName,
|
||||
string $viewPath = null,
|
||||
?string $viewPath = null,
|
||||
string $extension = 'php'
|
||||
): void
|
||||
{
|
||||
): void {
|
||||
$this->include(
|
||||
$viewName,
|
||||
$viewPath,
|
||||
@ -85,18 +85,18 @@ class View extends Neuron {
|
||||
/**
|
||||
* Renderiza código CSS.
|
||||
*
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
|
||||
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function css(
|
||||
string $viewName,
|
||||
string $viewPath = null,
|
||||
?string $viewPath = null,
|
||||
string $extension = 'css'
|
||||
): void
|
||||
{
|
||||
): void {
|
||||
header("Content-type: text/css");
|
||||
$this->include($viewName, $viewPath, $extension);
|
||||
}
|
||||
@ -104,18 +104,18 @@ class View extends Neuron {
|
||||
/**
|
||||
* Renderiza código Javascript.
|
||||
*
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
|
||||
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
|
||||
* @param string $extension (opcional) Extensión del archivo.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function js(
|
||||
string $viewName,
|
||||
string $viewPath = null,
|
||||
?string $viewPath = null,
|
||||
string $extension = 'js'
|
||||
): void
|
||||
{
|
||||
): void {
|
||||
header("Content-type: application/javascript");
|
||||
$this->include($viewName, $viewPath, $extension);
|
||||
}
|
||||
@ -153,12 +153,12 @@ class View extends Neuron {
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function route(string $path = '/'): string
|
||||
public static function route(string $path = '/'): string
|
||||
{
|
||||
if (defined('SITE_URL') && !empty(SITE_URL))
|
||||
return SITE_URL.substr($path,1);
|
||||
if (defined('SITE_URL') && !empty(SITE_URL)) {
|
||||
return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
}
|
||||
?>
|
||||
|
Reference in New Issue
Block a user