Compare commits

..

26 Commits

Author SHA1 Message Date
kj
e9126e7cde Fix: Implicitly marking parameter as nullable is deprecated.
PHP 8.4 deprecation.
2025-06-07 14:27:47 -03:00
kj
7169d2cae3 Fix: render is not using the defined extension. 2025-06-07 14:17:11 -03:00
kj
66b2bc0d91 Remove unnecesary php close. 2025-06-07 14:14:16 -03:00
kj
c8ab2aa2cc Remove unnecesary echo. 2025-05-20 12:49:20 -03:00
kj
1e302a9ea7 BREAKING CHANGE: Change unnecesary false return type. 2025-04-19 15:44:16 -03:00
kj
d0d0d4dc76 Verify if a valid http query string after run parse_str. 2025-02-20 08:22:47 -03:00
kj
595e9c1316 Save body request as a property. 2025-02-20 08:22:37 -03:00
kj
45abea5301 Add delete request params. 2025-02-20 06:28:03 -03:00
kj
d441f001ec Add type of items on array on dockblock for "all" method. 2025-02-03 16:04:39 -03:00
kj
19da122e05 Add type of items on array on dockblock for get method. 2025-02-03 16:02:27 -03:00
KJ
1a0164c8ed Change static methods to non-static and made onInvalid public. 2024-10-30 11:53:44 -04:00
KJ
ad9f8ec67d Remove unnecesary brackets. 2024-10-29 19:12:25 -04:00
KJ
31c5c63952 Remove innecesary return. 2024-10-29 19:10:47 -04:00
KJ
6aef212350 Fix className not returning the classname in the right format. 2024-10-25 10:40:57 -04:00
KJ
c600688725 Improve return array dockblocks. 2024-09-23 18:09:38 -04:00
KJ
3e27b1b7af Allow null on enum properties. 2024-09-23 15:06:44 -04:00
KJ
73b7b8f72a Change required valitator to not allow empty values and add exists.
The exists validator do the same as the old required.
2024-09-18 14:33:33 -04:00
KJ
7baad428ec Refactor request library. 2024-09-08 14:43:56 -04:00
KJ
3d2a607768 Fix where_in is wiping previous where/and/or.
For now, works as an AND, but maybe later, same as where will exists
new methods: AndIn and OrIN.
2024-08-30 16:26:03 -04:00
KJ
df424ffab5 Model properties now can be typed as enums.
With this PHP 8.0 support is dropped.
2024-08-27 19:01:02 -04:00
KJ
daf7250882 Catch and verify put and patch input values. 2024-08-13 10:22:44 -04:00
KJ
05cd83fd10 Remove unused variable. 2024-07-31 03:29:49 -04:00
KJ
6b470a181d Fix: Remove unnecesary parameter. 2024-07-10 09:06:51 -04:00
KJ
7beb161d2b Ensure db is in transaction to commit or rollback. 2024-06-04 07:18:30 -04:00
KJ
701caae7eb Change route method to static. 2024-05-29 13:24:20 -04:00
KJ
100bdfe006 Change private method to protected instead. 2024-05-28 22:27:20 -04:00
6 changed files with 179 additions and 123 deletions

View File

@ -7,18 +7,14 @@ spl_autoload_register(function ($className) {
$name = basename($fp); $name = basename($fp);
$dir = dirname($fp); $dir = dirname($fp);
$file = ROOT_CORE.'/'.$dir.'/'.$name.'.php'; $file = ROOT_CORE.'/'.$dir.'/'.$name.'.php';
if (file_exists($file)) { if (file_exists($file))
require_once $file; require_once $file;
return;
}
}); });
// Incluir routers // 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); require_once($file);
}
\Libs\Router::apply(); \Libs\Router::apply();
?>

View File

@ -85,7 +85,10 @@ class Model {
*/ */
public function rollBack(): bool public function rollBack(): bool
{ {
return static::db()->rollBack(); if ( static::db()->inTransaction())
return static::db()->rollBack();
else
return true;
} }
/** /**
@ -96,7 +99,10 @@ class Model {
*/ */
public function commit(): bool public function commit(): bool
{ {
return static::db()->commit(); if (static::db()->inTransaction())
return static::db()->commit();
else
return true;
} }
/** /**
@ -129,7 +135,6 @@ class Model {
$vars = json_encode(static::$queryVars); $vars = json_encode(static::$queryVars);
echo "<pre>";
throw new Exception( throw new Exception(
"\nError at query to database.\n" . "\nError at query to database.\n" .
"Query: $query\n" . "Query: $query\n" .
@ -236,11 +241,18 @@ class Model {
*/ */
protected static function getInstance(array $elem = []): static protected static function getInstance(array $elem = []): static
{ {
$class = get_called_class(); $class = get_called_class();
$instance = new $class; $instance = new $class;
$reflection = new ReflectionClass($instance);
$properties = $reflection->getProperties();
$propertyNames = array_column($properties, 'name');
foreach ($elem as $key => $value) { foreach ($elem as $key => $value) {
$instance->$key = $value; $index = array_search($key, $propertyNames);
if (is_numeric($index) && enum_exists($properties[$index]->getType()->getName()))
$instance->$key = $properties[$index]->getType()->getName()::tryfrom($value);
else
$instance->$key = $value;
} }
return $instance; return $instance;
@ -272,10 +284,14 @@ class Model {
$result[$value] = isset($this->$value) $result[$value] = isset($this->$value)
? $this->$value: null; ? $this->$value: null;
foreach ($result as $i => $property) foreach ($result as $i => $property) {
if (gettype($property) == 'boolean') if (gettype($property) == 'boolean')
$result[$i] = $property ? '1' : '0'; $result[$i] = $property ? '1' : '0';
if ($property instanceof \UnitEnum)
$result[$i] = $property->value;
}
return $result; return $result;
} }
@ -287,13 +303,8 @@ class Model {
*/ */
public static function className(): string public static function className(): string
{ {
return strtolower( return substr(
preg_replace( strrchr(get_called_class(), '\\'), 1
'/(?<!^)[A-Z]/', '_$0',
substr(
strrchr(get_called_class(), '\\'), 1
)
)
); );
} }
@ -308,7 +319,13 @@ class Model {
{ {
if (isset(static::$table)) if (isset(static::$table))
return static::$table; return static::$table;
return static::className().static::$tableSufix;
return strtolower(
preg_replace(
'/(?<!^)[A-Z]/', '_$0',
static::className()
)
).static::$tableSufix;
} }
/** /**
@ -432,7 +449,7 @@ class Model {
* @param string $operatorOrValue * @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina. * El operador o el valor a comparar como igual en caso de que $value no se defina.
* *
* @param string $value * @param string|null $value
* (opcional) El valor a comparar en la columna. * (opcional) El valor a comparar en la columna.
* *
* @param bool $no_filter * @param bool $no_filter
@ -442,10 +459,10 @@ class Model {
* @return static * @return static
*/ */
public static function where( public static function where(
string $column, string $column,
string $operatorOrValue, string $operatorOrValue,
string $value = null, ?string $value = null,
bool $no_filter = false bool $no_filter = false
): static ): static
{ {
return static::and( return static::and(
@ -465,7 +482,7 @@ class Model {
* @param string $operatorOrValue * @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina. * El operador o el valor a comparar como igual en caso de que $value no se defina.
* *
* @param string $value * @param string|null $value
* (opcional) El valor el valor a comparar en la columna. * (opcional) El valor el valor a comparar en la columna.
* *
* @param bool $no_filter * @param bool $no_filter
@ -475,10 +492,10 @@ class Model {
* @return static * @return static
*/ */
public static function and( public static function and(
string $column, string $column,
string $operatorOrValue, string $operatorOrValue,
string $value = null, ?string $value = null,
bool $no_filter = false bool $no_filter = false
): static ): static
{ {
if (is_null($value)) { if (is_null($value)) {
@ -506,7 +523,7 @@ class Model {
* @param string $operatorOrValue * @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina. * El operador o el valor a comparar como igual en caso de que $value no se defina.
* *
* @param string $value * @param string|null $value
* (opcional) El valor el valor a comparar en la columna. * (opcional) El valor el valor a comparar en la columna.
* *
* @param bool $no_filter * @param bool $no_filter
@ -516,10 +533,10 @@ class Model {
* @return static * @return static
*/ */
public static function or( public static function or(
string $column, string $column,
string $operatorOrValue, string $operatorOrValue,
string $value = null, ?string $value = null,
bool $no_filter = false bool $no_filter = false
): static ): static
{ {
if (is_null($value)) { if (is_null($value)) {
@ -564,9 +581,14 @@ class Model {
} }
if ($in) if ($in)
static::$querySelect['where'] = "$column IN (".join(', ', $arrIn).")"; $where_in = "$column IN (".join(', ', $arrIn).")";
else else
static::$querySelect['where'] = "$column NOT IN (".join(', ', $arrIn).")"; $where_in = "$column NOT IN (".join(', ', $arrIn).")";
if (static::$querySelect['where'] == '')
static::$querySelect['where'] = $where_in;
else
static::$querySelect['where'] .= " AND $where_in";
return new static(); return new static();
} }
@ -583,16 +605,16 @@ class Model {
* @param string $operatorOrColumnB * @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina. * Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
* *
* @param string $columnB * @param string|null $columnB
* (opcional) Columna a comparar para hacer el join. * (opcional) Columna a comparar para hacer el join.
* *
* @return static * @return static
*/ */
public static function leftJoin( public static function leftJoin(
string $table, string $table,
string $columnA, string $columnA,
string $operatorOrColumnB, string $operatorOrColumnB,
string $columnB = null ?string $columnB = null
): static ): static
{ {
if (is_null($columnB)) { if (is_null($columnB)) {
@ -617,16 +639,16 @@ class Model {
* @param string $operatorOrColumnB * @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina. * Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
* *
* @param string $columnB * @param string|null $columnB
* (opcional) Columna a comparar para hacer el join. * (opcional) Columna a comparar para hacer el join.
* *
* @return static * @return static
*/ */
public static function rightJoin( public static function rightJoin(
string $table, string $table,
string $columnA, string $columnA,
string $operatorOrColumnB, string $operatorOrColumnB,
string $columnB = null ?string $columnB = null
): static ): static
{ {
if (is_null($columnB)) { if (is_null($columnB)) {
@ -651,16 +673,16 @@ class Model {
* @param string $operatorOrColumnB * @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina. * Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
* *
* @param string $columnB * @param string|null $columnB
* (opcional) Columna a comparar para hacer el join. * (opcional) Columna a comparar para hacer el join.
* *
* @return static * @return static
*/ */
public static function innerJoin( public static function innerJoin(
string $table, string $table,
string $columnA, string $columnA,
string $operatorOrColumnB, string $operatorOrColumnB,
string $columnB = null ?string $columnB = null
): static ): static
{ {
if (is_null($columnB)) { if (is_null($columnB)) {
@ -801,20 +823,18 @@ class Model {
* @param string $search * @param string $search
* Contenido a buscar. * Contenido a buscar.
* *
* @param array $in * @param array|null $in
* (opcional) Columnas en las que se va a buscar (null para buscar en todas). * (opcional) Columnas en las que se va a buscar (null para buscar en todas).
* *
* @return static * @return static
*/ */
public static function search(string $search, array $in = null): static public static function search(string $search, ?array $in = null): static
{ {
if ($in == null) { if ($in == null) {
$className = get_called_class(); $className = get_called_class();
$in = array_keys((new $className())->getVars()); $in = array_keys((new $className())->getVars());
} }
$db = static::db();
$search = static::bindValue($search); $search = static::bindValue($search);
$where = []; $where = [];
@ -840,7 +860,7 @@ class Model {
* @param bool $resetQuery * @param bool $resetQuery
* (opcional) Indica si el query debe reiniciarse o no (por defecto es true). * (opcional) Indica si el query debe reiniciarse o no (por defecto es true).
* *
* @return array * @return array<static>
* Arreglo con instancias del la clase actual resultantes del query. * Arreglo con instancias del la clase actual resultantes del query.
*/ */
public static function get(bool $resetQuery = true): array public static function get(bool $resetQuery = true): array
@ -876,7 +896,7 @@ class Model {
/** /**
* Obtener todos los elementos del la tabla de la instancia actual. * Obtener todos los elementos del la tabla de la instancia actual.
* *
* @return array * @return array<static>
* Contiene un arreglo de instancias de la clase actual. * Contiene un arreglo de instancias de la clase actual.
*/ */
public static function all(): array public static function all(): array

View File

@ -15,10 +15,14 @@ namespace Libs;
class Request extends Neuron { class Request extends Neuron {
public Neuron $get; public Neuron $get;
public Neuron $post; public Neuron $post;
public Neuron $put;
public Neuron $patch;
public Neuron $delete;
public Neuron $json; public Neuron $json;
public Neuron $params; public Neuron $params;
public string $path; public string $path;
public string $error; public string $error;
public string $body;
public array $next; public array $next;
/** /**
@ -31,34 +35,57 @@ class Request extends Neuron {
$this->path = Router::currentPath(); $this->path = Router::currentPath();
$this->get = new Neuron($_GET); $this->get = new Neuron($_GET);
$this->post = new Neuron($_POST); $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"]) : ''; $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") if ($contentType === "application/json")
$this->json = new Neuron( $this->json = new Neuron(
(object) json_decode(trim(file_get_contents("php://input")), false) (object) json_decode(trim($this->body), false)
); );
else else {
$this->json = new Neuron(); $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(); $this->params = new Neuron();
} }
/** /**
* Inicia la validación que se haya configurado. * Corre las validaciones e intenta continuar con la pila de callbacks.
* *
* @return mixed * @return mixed
*/ */
public function validate(): mixed public function handle(): mixed
{ {
if ($_SERVER['REQUEST_METHOD'] == 'GET') if ($this->validate())
$actual = $this->get; return Middleware::next($this);
else
$actual = $this->post; 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) && if (Validator::validateList(static::paramRules(), $this->params) &&
Validator::validateList(static::getRules(), $this->get ) && Validator::validateList(static::getRules(), $this->get ) &&
Validator::validateList(static::rules(), $actual)) Validator::validateList(static::rules(), $actual))
return Middleware::next($this); return true;
if (isset(static::messages()[Validator::$lastFailed])) if (isset(static::messages()[Validator::$lastFailed]))
$error = static::messages()[Validator::$lastFailed]; $error = static::messages()[Validator::$lastFailed];
@ -67,7 +94,8 @@ class Request extends Neuron {
$error = 'Error: validation failed of '.preg_replace('/\./', ' as ', Validator::$lastFailed, 1); $error = 'Error: validation failed of '.preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
} }
return static::onInvalid($error); static::onInvalid($error);
return false;
} }
/** /**
@ -75,7 +103,7 @@ class Request extends Neuron {
* *
* @return array * @return array
*/ */
public static function rules(): array { public function rules(): array {
return []; return [];
} }
@ -84,7 +112,7 @@ class Request extends Neuron {
* *
* @return array * @return array
*/ */
public static function paramRules(): array { public function paramRules(): array {
return []; return [];
} }
@ -93,7 +121,7 @@ class Request extends Neuron {
* *
* @return array * @return array
*/ */
public static function getRules(): array { public function getRules(): array {
return []; return [];
} }
@ -102,7 +130,7 @@ class Request extends Neuron {
* *
* @return array * @return array
*/ */
public static function messages(): array { public function messages(): array {
return []; return [];
} }
@ -111,12 +139,11 @@ class Request extends Neuron {
* *
* @param string $error * @param string $error
* *
* @return mixed * @return void
*/ */
protected function onInvalid(string $error): mixed public function onInvalid(string $error): void
{ {
http_response_code(422); http_response_code(422);
print($error); print($error);
return null;
} }
} }

View File

@ -114,7 +114,7 @@ class Router {
* @return static * @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(); return new static();
@ -202,13 +202,13 @@ class Router {
* *
* @param string $path * @param string $path
* Ruta con pseudovariables. * Ruta con pseudovariables.
* @param callable $callback * @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida. * Callback que será llamado cuando la ruta configurada en $path coincida.
* *
* @return static * @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); return static::configure('get', $path, $callback);
} }
@ -218,13 +218,13 @@ class Router {
* *
* @param string $path * @param string $path
* Ruta con pseudovariables. * Ruta con pseudovariables.
* @param callable $callback * @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida. * Callback que será llamado cuando la ruta configurada en $path coincida.
* *
* @return static * @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); return static::configure('post', $path, $callback);
} }
@ -234,14 +234,14 @@ class Router {
* *
* @param string $path * @param string $path
* Ruta con pseudovariables. * Ruta con pseudovariables.
* @param callable $callback * @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida. * Callback que será llamado cuando la ruta configurada en $path coincida.
* *
* @return static * @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); return static::configure('put', $path, $callback);
} }
@ -251,13 +251,13 @@ class Router {
* *
* @param string $path * @param string $path
* Ruta con pseudovariables. * Ruta con pseudovariables.
* @param callable $callback * @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida. * Callback que será llamado cuando la ruta configurada en $path coincida.
* *
* @return static * @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); return static::configure('patch', $path, $callback);
} }
@ -267,13 +267,13 @@ class Router {
* *
* @param string $path * @param string $path
* Ruta con pseudovariables * Ruta con pseudovariables
* @param callable $callback * @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida. * Callback que será llamado cuando la ruta configurada en $path coincida.
* *
* @return static * @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); return static::configure('delete', $path, $callback);
} }
@ -292,11 +292,11 @@ class Router {
/** /**
* Aplica la configuración de rutas. * Aplica la configuración de rutas.
* *
* @param string $path (opcional) Ruta a usar. Si no se define, detecta la ruta actual. * @param string|null $path (opcional) Ruta a usar. Si no se define, detecta la ruta actual.
* *
* @return void * @return void
*/ */
public static function apply(string $path = null): void public static function apply(?string $path = null): void
{ {
$path = $path ?? static::currentPath(); $path = $path ?? static::currentPath();
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers $routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
@ -356,7 +356,7 @@ class Router {
// Llama a la validación y luego procesa la cola de callbacks // Llama a la validación y luego procesa la cola de callbacks
$request->next = $router['callback']; $request->next = $router['callback'];
$data = $request->validate($request); $data = $request->handle();
// Por defecto imprime como JSON si se retorna algo // Por defecto imprime como JSON si se retorna algo
if (isset($data)) { if (isset($data)) {

View File

@ -11,7 +11,8 @@
* | Regla | Descripción | * | Regla | Descripción |
* |----------+--------------------------------------------------------| * |----------+--------------------------------------------------------|
* | not | Niega la siguiente regla. Ej: not:float | * | not | Niega la siguiente regla. Ej: not:float |
* | required | Es requerido | * | 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 | * | number | Es numérico |
* | int | Es entero | * | int | Es entero |
* | float | Es un float | * | float | Es un float |
@ -90,7 +91,19 @@ class Validator {
} }
/** /**
* required * 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 * @param mixed $subject
* *
@ -98,7 +111,7 @@ class Validator {
*/ */
public static function required(mixed $subject): bool public static function required(mixed $subject): bool
{ {
return isset($subject); return isset($subject) && !empty($subject);
} }
/** /**

View File

@ -16,16 +16,16 @@ class View extends Neuron {
/** /**
* Incluye el archivo. * Incluye el archivo.
* *
* @param string $viewName Ruta relativa y el nommbre sin extensión del 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|null $viewPath (opcional) Ruta donde se encuentra la vista.
* @param string $extension (opcional) Extensión del archivo. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
*/ */
private function include( protected function include(
string $viewName, string $viewName,
string $viewPath = null, ?string $viewPath = null,
string $extension = 'php' string $extension = 'php'
): void ): void
{ {
$view = $this; $view = $this;
@ -44,7 +44,7 @@ class View extends Neuron {
* *
* @param string $viewName Ruta relativa y el nommbre sin 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 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|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. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
@ -52,27 +52,27 @@ class View extends Neuron {
public static function render( public static function render(
string $viewName, string $viewName,
array|Neuron $params = [], array|Neuron $params = [],
string $viewPath = null, ?string $viewPath = null,
string $extension = 'php' string $extension = 'php'
): void ): void
{ {
$instance = new View($params); $instance = new View($params);
$instance->html($viewName, $viewPath); $instance->html($viewName, $viewPath, $extension);
} }
/** /**
* Renderiza las vistas HTML * Renderiza las vistas HTML
* *
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views * @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|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. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
*/ */
public function html( public function html(
string $viewName, string $viewName,
string $viewPath = null, ?string $viewPath = null,
string $extension = 'php' string $extension = 'php'
): void ): void
{ {
$this->include( $this->include(
@ -85,16 +85,16 @@ class View extends Neuron {
/** /**
* Renderiza código CSS. * Renderiza código CSS.
* *
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views * @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|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. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
*/ */
public function css( public function css(
string $viewName, string $viewName,
string $viewPath = null, ?string $viewPath = null,
string $extension = 'css' string $extension = 'css'
): void ): void
{ {
header("Content-type: text/css"); header("Content-type: text/css");
@ -104,16 +104,16 @@ class View extends Neuron {
/** /**
* Renderiza código Javascript. * Renderiza código Javascript.
* *
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views * @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|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. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
*/ */
public function js( public function js(
string $viewName, string $viewName,
string $viewPath = null, ?string $viewPath = null,
string $extension = 'js' string $extension = 'js'
): void ): void
{ {
header("Content-type: application/javascript"); header("Content-type: application/javascript");
@ -153,7 +153,7 @@ class View extends Neuron {
* *
* @return string * @return string
*/ */
public function route(string $path = '/'): string public static function route(string $path = '/'): string
{ {
if (defined('SITE_URL') && !empty(SITE_URL)) if (defined('SITE_URL') && !empty(SITE_URL))
return rtrim(SITE_URL, '/').'/'.ltrim($path, '/'); return rtrim(SITE_URL, '/').'/'.ltrim($path, '/');