Compare commits

..

42 Commits

Author SHA1 Message Date
kj
b19e7d8789 Remove a forgotten debug line. 2025-09-07 18:52:33 -03:00
kj
4dfdb52519 Remove unnecessary and really never-used tableSufix property. 2025-09-07 15:25:48 -03:00
kj
b0891885f9 BREAKING CHANGE: Make select, from, and setNull methods variadic. 2025-09-07 15:20:06 -03:00
kj
b282d5479f Convert object/database naming conventions.
Adhere to PSR-12 by converting object properties to "lowerCamelCase" for objects
and "snake_case" for database interactions.

Backward compatibility is maintained: object properties already using
"snake_case" will continue to work without issue.
2025-09-07 15:01:45 -03:00
kj
c9f467345b BREAKING CHANGE: Adhere to PSR-12 coding standards.
- Model: where_in method was renamed as whereIn.
2025-09-07 11:07:07 -03:00
kj
0f46848d15 Remove the predefined 'id' property.
This property is not necessary and gives less flexibility.
2025-08-15 14:51:16 -03:00
kj
b2cb8d6883 Allow statically call beginTransaction, rollback and commit methods. 2025-07-15 18:12:41 -03:00
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
KJ
f1b79fdbc0 Add http code 422 on verification failed. 2024-05-25 17:41:33 -04:00
KJ
406f9a10a1 Add head comment. 2024-05-25 17:19:08 -04:00
KJ
cc3cb6be41 Fix: a return was forgot. 2024-05-25 17:11:07 -04:00
KJ
59fff2a586 Add validation on Request. 2024-05-25 16:59:59 -04:00
KJ
cd1685d2e7 fix on a docblock. 2024-05-21 15:06:02 -04:00
KJ
b85fb7e034 Allow configure SITE_URL with or without slash at end. 2024-05-16 13:48:49 -04:00
KJ
a10308a8f6 Fix route and redirect methods error when path not start with slash. 2024-05-16 13:20:35 -04:00
KJ
9a1e5a2379 Add some explanatory comments to config. 2024-05-14 02:54:23 -04:00
KJ
fa60ec5bb4 Move constant definition to config.php 2024-05-14 02:53:39 -04:00
10 changed files with 886 additions and 452 deletions

View File

@ -1,11 +1,15 @@
<?php <?php
// Configuración de la base de datos
define('DB_TYPE', 'mysql'); define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost'); define('DB_HOST', 'localhost');
define('DB_NAME', ''); define('DB_NAME', '');
define('DB_USER', ''); define('DB_USER', '');
define('DB_PASS', ''); define('DB_PASS', '');
//define('SITE_URL', ''); // Configuración del sitio
define('SITE_URL', '');
// Configuración avanzada
define('ROOT_DIR', __DIR__); define('ROOT_DIR', __DIR__);
?> define('ROOT_CORE', ROOT_DIR . '/src');

View File

@ -1,26 +1,23 @@
<?php <?php
require_once('config.php');
define('ROOT_CORE', ROOT_DIR.'/src'); require_once('config.php');
// Incluir clases // Incluir clases
spl_autoload_register(function ($className) { spl_autoload_register(function ($className) {
$fp = str_replace('\\','/',$className); $fp = str_replace('\\', '/', $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

@ -1,4 +1,11 @@
<?php <?php
namespace Libs;
use Exception;
use PDO;
use PDOException;
/** /**
* Database - DuckBrain * Database - DuckBrain
* *
@ -8,38 +15,33 @@
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
class Database extends PDO
{
private static array $databases = [];
namespace Libs; private function __construct()
{
use PDO; }
use PDOException;
use Exception;
class Database extends PDO {
static private array $databases = [];
private function __construct() {}
/** /**
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO). * Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
* *
* @return PDO * @return PDO
*/ */
static public function getInstance( public static function getInstance(
string $type = 'mysql', string $type = 'mysql',
string $host = 'localhost', string $host = 'localhost',
string $name = '', string $name = '',
string $user = '', string $user = '',
string $pass = '', string $pass = '',
): PDO ): PDO {
{ $key = $type . '/' . $host . '/' . $name . '/' . $user;
$key = $type.'/'.$host.'/'.$name.'/'.$user;
if (empty(static::$databases[$key])) { if (empty(static::$databases[$key])) {
if ($type == 'sqlite') { if ($type == 'sqlite') {
$dsn = $type .':'. $name; $dsn = $type . ':' . $name;
} else } else {
$dsn = $type.':dbname='.$name.';host='.$host; $dsn = $type . ':dbname=' . $name . ';host=' . $host;
}
try { try {
static::$databases[$key] = new PDO($dsn, $user, $pass); static::$databases[$key] = new PDO($dsn, $user, $pass);
@ -55,4 +57,3 @@ class Database extends PDO {
return static::$databases[$key]; return static::$databases[$key];
} }
} }
?>

View File

@ -1,4 +1,7 @@
<?php <?php
namespace Libs;
/** /**
* Middleware - DuckBrain * Middleware - DuckBrain
* *
@ -8,11 +11,8 @@
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
class Middleware
namespace Libs; {
class Middleware {
/** /**
* Llama al siguiente callback. * Llama al siguiente callback.
* *

View File

@ -1,4 +1,14 @@
<?php <?php
namespace Libs;
use AllowDynamicProperties;
use Exception;
use PDO;
use PDOException;
use ReflectionClass;
use ReflectionProperty;
/** /**
* Model - DuckBrain * Model - DuckBrain
* *
@ -10,29 +20,16 @@
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
namespace Libs;
use Libs\Database;
use PDO;
use PDOException;
use Exception;
use ReflectionClass;
use ReflectionProperty;
use AllowDynamicProperties;
#[AllowDynamicProperties] #[AllowDynamicProperties]
class Model { class Model
{
public ?int $id = null;
protected array $toNull = []; protected array $toNull = [];
static protected string $primaryKey = 'id'; protected static string $primaryKey = 'id';
static protected array $ignoreSave = ['id']; protected static array $ignoreSave = ['id'];
static protected array $forceSave = []; protected static array $forceSave = [];
static protected string $table; protected static string $table;
static protected string $tableSufix = 's'; protected static array $queryVars = [];
static protected array $queryVars = []; protected static array $querySelect = [
static protected array $querySelect = [
'select' => ['*'], 'select' => ['*'],
'where' => '', 'where' => '',
'from' => '', 'from' => '',
@ -41,7 +38,7 @@ class Model {
'innerJoin' => '', 'innerJoin' => '',
'orderBy' => '', 'orderBy' => '',
'groupBy' => '', 'groupBy' => '',
'limit' => '' 'limit' => '',
]; ];
/** /**
@ -51,12 +48,12 @@ class Model {
*/ */
protected static function db(): PDO protected static function db(): PDO
{ {
if (DB_TYPE == 'sqlite') if (DB_TYPE == 'sqlite') {
return Database::getInstance( return Database::getInstance(
type: DB_TYPE, type: DB_TYPE,
name: DB_NAME name: DB_NAME
); );
else } else {
return Database::getInstance( return Database::getInstance(
DB_TYPE, DB_TYPE,
DB_HOST, DB_HOST,
@ -65,6 +62,7 @@ class Model {
DB_PASS DB_PASS
); );
} }
}
/** /**
* Ejecuta PDO::beginTransaction para iniciar una transacción. * Ejecuta PDO::beginTransaction para iniciar una transacción.
@ -72,7 +70,7 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function beginTransaction(): bool public static function beginTransaction(): bool
{ {
return static::db()->beginTransaction(); return static::db()->beginTransaction();
} }
@ -83,9 +81,13 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function rollBack(): bool public static function rollBack(): bool
{ {
if (static::db()->inTransaction()) {
return static::db()->rollBack(); return static::db()->rollBack();
} else {
return true;
}
} }
/** /**
@ -94,9 +96,13 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function commit(): bool public static function commit(): bool
{ {
if (static::db()->inTransaction()) {
return static::db()->commit(); return static::db()->commit();
} else {
return true;
}
} }
/** /**
@ -124,12 +130,12 @@ class Model {
$prepared = $db->prepare($query); $prepared = $db->prepare($query);
$prepared->execute(static::$queryVars); $prepared->execute(static::$queryVars);
} catch (PDOException $e) { } catch (PDOException $e) {
if ($db->inTransaction()) if ($db->inTransaction()) {
$db->rollBack(); $db->rollBack();
}
$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" .
@ -140,8 +146,9 @@ class Model {
$result = $prepared->fetchAll(); $result = $prepared->fetchAll();
if ($resetQuery) if ($resetQuery) {
static::resetQuery(); static::resetQuery();
}
return $result; return $result;
} }
@ -161,7 +168,7 @@ class Model {
'innerJoin' => '', 'innerJoin' => '',
'orderBy' => '', 'orderBy' => '',
'groupBy' => '', 'groupBy' => '',
'limit' => '' 'limit' => '',
]; ];
static::$queryVars = []; static::$queryVars = [];
} }
@ -175,33 +182,41 @@ class Model {
*/ */
protected static function buildQuery(): string protected static function buildQuery(): string
{ {
$sql = 'SELECT '.join(', ', static::$querySelect['select']); $sql = 'SELECT ' . join(', ', static::$querySelect['select']);
if (static::$querySelect['from'] != '') if (static::$querySelect['from'] != '') {
$sql .= ' FROM '.static::$querySelect['from']; $sql .= ' FROM ' . static::$querySelect['from'];
else } else {
$sql .= ' FROM '.static::table(); $sql .= ' FROM ' . static::table();
}
if(static::$querySelect['innerJoin'] != '') if (static::$querySelect['innerJoin'] != '') {
$sql .= static::$querySelect['innerJoin']; $sql .= static::$querySelect['innerJoin'];
}
if (static::$querySelect['leftJoin'] != '') if (static::$querySelect['leftJoin'] != '') {
$sql .= static::$querySelect['leftJoin']; $sql .= static::$querySelect['leftJoin'];
}
if(static::$querySelect['rightJoin'] != '') if (static::$querySelect['rightJoin'] != '') {
$sql .= static::$querySelect['rightJoin']; $sql .= static::$querySelect['rightJoin'];
}
if (static::$querySelect['where'] != '') if (static::$querySelect['where'] != '') {
$sql .= ' WHERE '.static::$querySelect['where']; $sql .= ' WHERE ' . static::$querySelect['where'];
}
if (static::$querySelect['groupBy'] != '') if (static::$querySelect['groupBy'] != '') {
$sql .= ' GROUP BY '.static::$querySelect['groupBy']; $sql .= ' GROUP BY ' . static::$querySelect['groupBy'];
}
if (static::$querySelect['orderBy'] != '') if (static::$querySelect['orderBy'] != '') {
$sql .= ' ORDER BY '.static::$querySelect['orderBy']; $sql .= ' ORDER BY ' . static::$querySelect['orderBy'];
}
if (static::$querySelect['limit'] != '') if (static::$querySelect['limit'] != '') {
$sql .= ' LIMIT '.static::$querySelect['limit']; $sql .= ' LIMIT ' . static::$querySelect['limit'];
}
return $sql; return $sql;
} }
@ -219,7 +234,7 @@ class Model {
*/ */
private static function bindValue(string $value): string private static function bindValue(string $value): string
{ {
$index = ':v_'.count(static::$queryVars); $index = ':v_' . count(static::$queryVars);
static::$queryVars[$index] = $value; static::$queryVars[$index] = $value;
return $index; return $index;
} }
@ -237,10 +252,24 @@ 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_map(function ($property) {
return static::camelCaseToSnakeCase($property->name);
}, $properties);
foreach ($elem as $key => $value) { foreach ($elem as $key => $value) {
$instance->$key = $value; $index = array_search($key, $propertyNames);
if (is_numeric($index)) {
if (enum_exists($properties[$index]->getType()->getName())) {
$instance->{$properties[$index]->name} = $properties[$index]->getType()->getName()::tryfrom($value);
} else {
$instance->{$properties[$index]->name} = $value;
}
} else {
$instance->{static::snakeCaseToCamelCase($key)} = $value;
}
} }
return $instance; return $instance;
@ -261,20 +290,27 @@ class Model {
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$result = []; $result = [];
foreach($properties as $property) foreach ($properties as $property) {
$result[$property->name] = isset($this->{$property->name}) if (!in_array($property->name, static::$ignoreSave)) {
$result[$this->camelCaseToSnakeCase($property->name)] = isset($this->{$property->name})
? $this->{$property->name} : null; ? $this->{$property->name} : null;
}
}
foreach (static::$ignoreSave as $del) foreach (static::$forceSave as $value) {
unset($result[$del]);
foreach (static::$forceSave as $value)
$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 ?? $property->name;
}
}
return $result; return $result;
} }
@ -283,17 +319,13 @@ class Model {
* Devuelve el nombre de la clase actual aunque sea una clase extendida. * Devuelve el nombre de la clase actual aunque sea una clase extendida.
* *
* @return string * @return string
* Devuelve el nombre de la clase actual. *
*/ */
public static function className(): string public static function className(): string
{ {
return strtolower( return substr(
preg_replace( strrchr(get_called_class(), '\\'),
'/(?<!^)[A-Z]/', '_$0', 1
substr(
strrchr(get_called_class(), '\\'), 1
)
)
); );
} }
@ -306,9 +338,43 @@ class Model {
*/ */
protected static function table(): string protected static function table(): string
{ {
if (isset(static::$table)) if (isset(static::$table)) {
return static::$table; return static::$table;
return static::className().static::$tableSufix; }
return static::camelCaseToSnakeCase(static::className()) . 's';
}
/**
* Convierte de lowerCamelCase a snake_case
*
* @param string $string
*
* @return string
*/
protected static function camelCaseToSnakeCase(string $string): string
{
return strtolower(
preg_replace(
'/(?<!^)[A-Z]/',
'_$0',
$string
)
);
}
/**
* Convierte de snake_case a lowerCamelCase
*
* @param string $string
*
* @return string
*/
protected static function snakeCaseToCamelCase(string $string): string
{
return preg_replace_callback('/_([a-z])/', function ($matches) {
return strtoupper($matches[1]);
}, $string);
} }
/** /**
@ -321,22 +387,23 @@ class Model {
foreach ($atts as $key => $value) { foreach ($atts as $key => $value) {
if (isset($value)) { if (isset($value)) {
if (in_array($key, $this->toNull)) if (in_array($key, $this->toNull)) {
$set[]="$key=NULL"; $set[] = "$key=NULL";
else { } else {
$set[]="$key=:$key"; $set[] = "$key=:$key";
static::$queryVars[':'.$key] = $value; static::$queryVars[':' . $key] = $value;
} }
} else { } else {
if (in_array($key, $this->toNull)) if (in_array($key, $this->toNull)) {
$set[]="$key=NULL"; $set[] = "$key=NULL";
}
} }
} }
$table = static::table(); $table = static::table();
$pk = static::$primaryKey; $pk = static::$primaryKey;
$pkv = $this->$pk; $pkv = $this->$pk;
$sql = "UPDATE $table SET ".join(', ', $set)." WHERE $pk='$pkv'"; $sql = "UPDATE $table SET " . join(', ', $set) . " WHERE $pk='$pkv'";
static::query($sql); static::query($sql);
} }
@ -359,7 +426,7 @@ class Model {
} }
$table = static::table(); $table = static::table();
$sql = "INSERT INTO $table (".join(', ', $into).") VALUES (".join(', ', $values).")"; $sql = "INSERT INTO $table (" . join(', ', $into) . ") VALUES (" . join(', ', $values) . ")";
static::query($sql); static::query($sql);
$pk = static::$primaryKey; $pk = static::$primaryKey;
@ -374,17 +441,19 @@ class Model {
public function save(): void public function save(): void
{ {
$pk = static::$primaryKey; $pk = static::$primaryKey;
if (isset($this->$pk)) if (isset($this->$pk)) {
$this->update(); $this->update();
else } else {
$this->add(); $this->add();
} }
}
/** /**
* Elimina el objeto actual de la base de datos. * Elimina el objeto actual de la base de datos.
* @return void * @return void
*/ */
public function delete(): void { public function delete(): void
{
$table = static::table(); $table = static::table();
$pk = static::$primaryKey; $pk = static::$primaryKey;
$sql = "DELETE FROM $table WHERE $pk=:$pk"; $sql = "DELETE FROM $table WHERE $pk=:$pk";
@ -401,7 +470,7 @@ class Model {
* *
* @return static * @return static
*/ */
public static function select(array $columns): static public static function select(...$columns): static
{ {
static::$querySelect['select'] = $columns; static::$querySelect['select'] = $columns;
@ -416,7 +485,7 @@ class Model {
* *
* @return static * @return static
*/ */
public static function from(array $tables): static public static function from(...$tables): static
{ {
static::$querySelect['from'] = join(', ', $tables); static::$querySelect['from'] = join(', ', $tables);
@ -432,7 +501,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
@ -444,10 +513,9 @@ class Model {
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(
$column, $column,
$operatorOrValue, $operatorOrValue,
@ -465,7 +533,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
@ -477,22 +545,23 @@ class Model {
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)) {
$value = $operatorOrValue; $value = $operatorOrValue;
$operatorOrValue = '='; $operatorOrValue = '=';
} }
if (!$no_filter) if (!$no_filter) {
$value = static::bindValue($value); $value = static::bindValue($value);
}
if (static::$querySelect['where'] == '') if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = "$column $operatorOrValue $value"; static::$querySelect['where'] = "$column $operatorOrValue $value";
else } else {
static::$querySelect['where'] .= " AND $column $operatorOrValue $value"; static::$querySelect['where'] .= " AND $column $operatorOrValue $value";
}
return new static(); return new static();
} }
@ -506,7 +575,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
@ -518,22 +587,23 @@ class Model {
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)) {
$value = $operatorOrValue; $value = $operatorOrValue;
$operatorOrValue = '='; $operatorOrValue = '=';
} }
if (!$no_filter) if (!$no_filter) {
$value = static::bindValue($value); $value = static::bindValue($value);
}
if (static::$querySelect['where'] == '') if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = "$column $operatorOrValue $value"; static::$querySelect['where'] = "$column $operatorOrValue $value";
else } else {
static::$querySelect['where'] .= " OR $column $operatorOrValue $value"; static::$querySelect['where'] .= " OR $column $operatorOrValue $value";
}
return new static(); return new static();
} }
@ -552,21 +622,27 @@ class Model {
* *
* @return static * @return static
*/ */
public static function where_in( public static function whereIn(
string $column, string $column,
array $arr, array $arr,
bool $in = true bool $in = true
): static ): static {
{
$arrIn = []; $arrIn = [];
foreach($arr as $value) { foreach ($arr as $value) {
$arrIn[] = static::bindValue($value); $arrIn[] = static::bindValue($value);
} }
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();
} }
@ -581,9 +657,10 @@ class Model {
* Columna a comparar para hacer el join. * Columna a comparar para hacer el join.
* *
* @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
@ -592,9 +669,8 @@ class Model {
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)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -615,9 +691,10 @@ class Model {
* Columna a comparar para hacer el join. * Columna a comparar para hacer el join.
* *
* @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
@ -626,9 +703,8 @@ class Model {
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)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -649,9 +725,10 @@ class Model {
* Columna a comparar para hacer el join. * Columna a comparar para hacer el join.
* *
* @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
@ -660,9 +737,8 @@ class Model {
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)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -700,10 +776,11 @@ class Model {
*/ */
public static function limit(int $offsetOrQuantity, ?int $quantity = null): static public static function limit(int $offsetOrQuantity, ?int $quantity = null): static
{ {
if (is_null($quantity)) if (is_null($quantity)) {
static::$querySelect['limit'] = $offsetOrQuantity; static::$querySelect['limit'] = $offsetOrQuantity;
else } else {
static::$querySelect['limit'] = $offsetOrQuantity.', '.$quantity; static::$querySelect['limit'] = $offsetOrQuantity . ', ' . $quantity;
}
return new static(); return new static();
} }
@ -727,10 +804,11 @@ class Model {
return new static(); return new static();
} }
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC')) if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC')) {
$order = 'ASC'; $order = 'ASC';
}
static::$querySelect['orderBy'] = $value.' '.$order; static::$querySelect['orderBy'] = $value . ' ' . $order;
return new static(); return new static();
} }
@ -749,22 +827,25 @@ class Model {
*/ */
public static function count(bool $resetQuery = true, bool $useLimit = false): int public static function count(bool $resetQuery = true, bool $useLimit = false): int
{ {
if (!$resetQuery) if (!$resetQuery) {
$backup = [ $backup = [
'select' => static::$querySelect['select'], 'select' => static::$querySelect['select'],
'limit' => static::$querySelect['limit'], 'limit' => static::$querySelect['limit'],
'orderBy' => static::$querySelect['orderBy'] 'orderBy' => static::$querySelect['orderBy'],
]; ];
}
if ($useLimit && static::$querySelect['limit'] != '') { if ($useLimit && static::$querySelect['limit'] != '') {
static::$querySelect['select'] = ['1']; static::$querySelect['select'] = ['1'];
static::$querySelect['orderBy'] = ''; static::$querySelect['orderBy'] = '';
$sql = 'SELECT COUNT(1) AS quantity FROM ('.static::buildQuery().') AS counted'; $sql = 'SELECT COUNT(1) AS quantity FROM (' . static::buildQuery() . ') AS counted';
$queryResult = static::query($sql, $resetQuery); $queryResult = static::query($sql, $resetQuery);
$result = $queryResult[0]['quantity']; $result = $queryResult[0]['quantity'];
} else { } else {
static::$querySelect['select'] = ["COUNT(".static::table().".".static::$primaryKey.") as quantity"]; static::$querySelect['select'] = [
"COUNT(" . static::table() . "." . static::$primaryKey . ") as quantity",
];
static::$querySelect['limit'] = '1'; static::$querySelect['limit'] = '1';
static::$querySelect['orderBy'] = ''; static::$querySelect['orderBy'] = '';
@ -801,35 +882,37 @@ 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 = [];
if (DB_TYPE == 'sqlite') if (DB_TYPE == 'sqlite') {
foreach($in as $row) foreach ($in as $row) {
$where[] = "$row LIKE '%' || $search || '%'"; $where[] = "$row LIKE '%' || $search || '%'";
else }
foreach($in as $row) } else {
foreach ($in as $row) {
$where[] = "$row LIKE CONCAT('%', $search, '%')"; $where[] = "$row LIKE CONCAT('%', $search, '%')";
}
}
if (static::$querySelect['where']=='') if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = join(' OR ', $where); static::$querySelect['where'] = join(' OR ', $where);
else } else {
static::$querySelect['where'] = static::$querySelect['where'] .' AND ('.join(' OR ', $where).')'; static::$querySelect['where'] = static::$querySelect['where'] . ' AND (' . join(' OR ', $where) . ')';
}
return new static(); return new static();
} }
@ -840,7 +923,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
@ -864,7 +947,7 @@ class Model {
* (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 static|null * @return static|null
* Puede retornar un objeto static o null. * Puede retornar una instancia de la clase actual o null.
*/ */
public static function getFirst(bool $resetQuery = true): ?static public static function getFirst(bool $resetQuery = true): ?static
{ {
@ -876,18 +959,19 @@ 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
{ {
$sql = 'SELECT * FROM '.static::table(); $sql = 'SELECT * FROM ' . static::table();
$result = static::query($sql); $result = static::query($sql);
$instances = []; $instances = [];
foreach ($result as $row) foreach ($result as $row) {
$instances[] = static::getInstance($row); $instances[] = static::getInstance($row);
}
return $instances; return $instances;
} }
@ -896,22 +980,24 @@ class Model {
* Permite definir como nulo el valor de un atributo. * Permite definir como nulo el valor de un atributo.
* Sólo funciona para actualizar un elemento de la BD, no para insertar. * Sólo funciona para actualizar un elemento de la BD, no para insertar.
* *
* @param string|array $atts * @param array $attributes
* Atributo o arreglo de atributos que se definirán como nulos. * Atributo o arreglo de atributos que se definirán como nulos.
* *
* @return void * @return void
*/ */
public function setNull(string|array $atts): void public function setNull(...$attributes): void
{ {
if (is_array($atts)) { if (is_array($attributes)) {
foreach ($atts as $att) foreach ($attributes as $att) {
if (!in_array($att, $this->toNull)) if (!in_array($att, $this->toNull)) {
$this->toNull[] = $att; $this->toNull[] = $att;
}
}
return; return;
} }
if (!in_array($atts, $this->toNull)) if (!in_array($attributes, $this->toNull)) {
$this->toNull[] = $atts; $this->toNull[] = $attributes;
}
} }
} }
?>

View File

@ -1,27 +1,27 @@
<?php <?php
namespace Libs;
use AllowDynamicProperties;
/** /**
* Neuron - DuckBrain * Neuron - DuckBrain
* *
* Neuron, sirve para crear un objeto que alojará valores, pero * Neuron, sirve para crear un objeto que alojará valores.
* además tiene la característica especial de que al intentar * Además, tiene la característica especial de que al intentar
* acceder a un atributo que no está definido devolerá nulo en * acceder a una propiedad no definida, devolverá null en
* lugar de generar un error php notice que indica que se está * lugar de generar un aviso (PHP notice) por variable o propiedad no definida.
* intentando acceder a un valor no definido.
* *
* El constructor recibe un objeto o arreglo con los valores que * El constructor acepta un objeto o un arreglo que contiene los
* estarán definidos. * valores que estarán definidos.
* *
* @author KJ * @author KJ
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
namespace Libs;
use AllowDynamicProperties;
#[AllowDynamicProperties] #[AllowDynamicProperties]
class Neuron { class Neuron
{
/** /**
* __construct * __construct
* *
@ -29,15 +29,19 @@ class Neuron {
*/ */
public function __construct(...$data) public function __construct(...$data)
{ {
if (count($data) === 1 && if (
count($data) === 1 &&
isset($data[0]) && isset($data[0]) &&
(is_array($data[0]) || (is_array($data[0]) ||
is_object($data[0]))) is_object($data[0]))
) {
$data = $data[0]; $data = $data[0];
}
foreach($data as $key => $value) foreach ($data as $key => $value) {
$this->{$key} = $value; $this->{$key} = $value;
} }
}
/** /**
* __get * __get
@ -50,5 +54,3 @@ class Neuron {
return null; return null;
} }
} }
?>

View File

@ -1,4 +1,7 @@
<?php <?php
namespace Libs;
/** /**
* Request - DuckBrain * Request - DuckBrain
* *
@ -9,50 +12,151 @@
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
class Request extends Neuron
namespace Libs; {
class Request extends Neuron {
/**
* @var Neuron $get Objeto con todos los valores de $_GET.
*/
public Neuron $get; public Neuron $get;
/**
* @var Neuron $post Objeto con todos los valores de $_POST.
*/
public Neuron $post; public Neuron $post;
/** public Neuron $put;
* @var Neuron $json Objeto con todos los valores json enviados. public Neuron $patch;
*/ public Neuron $delete;
public Neuron $json; public Neuron $json;
/**
* @var mixed $params Objeto con todos los valores pseudovariables de la uri.
*/
public Neuron $params; public Neuron $params;
/**
* @var mixed $path Ruta actual tomando como raíz la instalación de DuckBrain.
*/
public string $path; public string $path;
public string $error;
public string $body;
public array $next;
/** /**
* __construct * __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->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();
} }
/**
* 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);
}
} }

View File

@ -1,4 +1,7 @@
<?php <?php
namespace Libs;
/** /**
* Router - DuckBrain * Router - DuckBrain
* *
@ -10,10 +13,8 @@
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
class Router
namespace Libs; {
class Router {
private static $get = []; private static $get = [];
private static $post = []; private static $post = [];
private static $put = []; private static $put = [];
@ -28,7 +29,7 @@ class Router {
* *
* @return void * @return void
*/ */
public static function defaultNotFound (): void public static function defaultNotFound(): void
{ {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>'; echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
@ -37,7 +38,9 @@ class Router {
/** /**
* __construct * __construct
*/ */
private function __construct() {} private function __construct()
{
}
/** /**
* Parsea para deectar las pseudovariables (ej: {variable}) * Parsea para deectar las pseudovariables (ej: {variable})
@ -62,12 +65,13 @@ class Router {
$path = preg_replace( $path = preg_replace(
['/\\\{\w+\\\}/s'], ['/\\\{\w+\\\}/s'],
['([^\/]+)'], ['([^\/]+)'],
$path); $path
);
return [ return [
'path' => $path, 'path' => $path,
'callback' => [$callback], 'callback' => [$callback],
'paramNames' => $paramNames 'paramNames' => $paramNames,
]; ];
} }
@ -82,8 +86,9 @@ class Router {
*/ */
public static function basePath(): string public static function basePath(): string
{ {
if (defined('SITE_URL') && !empty(SITE_URL)) if (defined('SITE_URL') && !empty(SITE_URL)) {
return parse_url(SITE_URL, PHP_URL_PATH); return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/') . '/';
}
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR); return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
} }
@ -100,7 +105,7 @@ class Router {
*/ */
public static function redirect(string $path): void public static function redirect(string $path): void
{ {
header('Location: '.static::basePath().substr($path,1)); header('Location: ' . static::basePath() . ltrim($path, '/'));
exit; exit;
} }
@ -114,20 +119,22 @@ 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();
}
$method = static::$last[0]; $method = static::$last[0];
$index = static::$last[1]; $index = static::$last[1];
if (isset($priority) && $priority <= 0) if (isset($priority) && $priority <= 0) {
$priority = 1; $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; static::$$method[$index]['callback'][] = $callback;
else { } else {
static::$$method[$index]['callback'] = array_merge( static::$$method[$index]['callback'] = array_merge(
array_slice(static::$$method[$index]['callback'], 0, $priority), array_slice(static::$$method[$index]['callback'], 0, $priority),
[$callback], [$callback],
@ -147,8 +154,9 @@ class Router {
*/ */
public static function reconfigure(callable $callback): static public static function reconfigure(callable $callback): static
{ {
if (empty(static::$last)) if (empty(static::$last)) {
return new static(); return new static();
}
$method = static::$last[0]; $method = static::$last[0];
$index = static::$last[1]; $index = static::$last[1];
@ -181,19 +189,21 @@ class Router {
$path = preg_replace( $path = preg_replace(
['/\\\{\w+\\\}/s'], ['/\\\{\w+\\\}/s'],
['([^\/]+)'], ['([^\/]+)'],
$path); $path
);
foreach(static::$$method as $index => $router) foreach (static::$$method as $index => $router) {
if ($router['path'] == $path) { if ($router['path'] == $path) {
static::$last = [$method, $index]; static::$last = [$method, $index];
break; break;
} }
}
return new static(); return new static();
} }
static::$$method[] = static::parse($path, $callback); static::$$method[] = static::parse($path, $callback);
static::$last = [$method, count(static::$$method)-1]; static::$last = [$method, count(static::$$method) - 1];
return new static(); return new static();
} }
@ -202,13 +212,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 +228,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 +244,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 +261,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 +277,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);
} }
@ -283,36 +293,27 @@ class Router {
* *
* @return string * @return string
*/ */
public static function currentPath() : string public static function currentPath(): string
{ {
return preg_replace('/'.preg_quote(static::basePath(), '/').'/', return preg_replace(
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1); '/' . 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 * @return void
*/ */
public static function apply(): void public static function apply(?string $path = null): void
{ {
$path = static::currentPath(); $path = $path ?? static::currentPath();
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers configurados $routers = match ($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
'POST' => static::$post, 'POST' => static::$post,
'PUT' => static::$put, 'PUT' => static::$put,
'PATCH' => static::$patch, 'PATCH' => static::$patch,
@ -320,25 +321,61 @@ class Router {
default => static::$get default => static::$get
}; };
$req = new Request(static::currentPath());
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual 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]); unset($matches[0]);
// Comprobando pseudo variables en la ruta // 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]);
}
}
// 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])) { if (isset($matches[1])) {
foreach ($matches as $index => $match) { foreach ($matches as $index => $match) {
$paramName = $router['paramNames'][$index-1]; $paramName = $router['paramNames'][$index - 1];
$req->params->$paramName = urldecode($match[0]); $request->params->$paramName = urldecode($match[0]);
} }
} }
// Llamar al último callback configurado // Llama a la validación y luego procesa la cola de callbacks
$next = array_pop($router['callback']); $request->next = $router['callback'];
$req->next = $router['callback']; $data = $request->handle();
$data = call_user_func_array($next, [$req]);
// Por defecto imprime como JSON si se retorna algo
if (isset($data)) { if (isset($data)) {
header('Content-Type: application/json'); header('Content-Type: application/json');
print(json_encode($data)); print(json_encode($data));
@ -349,7 +386,6 @@ class Router {
} }
// Si no hay router que coincida llamamos a $notFoundCallBack // 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
View 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);
}
}

View File

@ -1,4 +1,7 @@
<?php <?php
namespace Libs;
/** /**
* View - DuckBrain * View - DuckBrain
* *
@ -7,44 +10,42 @@
* @author KJ * @author KJ
* @website https://kj2.me * @website https://kj2.me
* @licence MIT * @licence MIT
*/ */
class View extends Neuron
namespace Libs; {
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 {
{ if (
$view = $this; isset($viewPath) &&
file_exists("$viewPath$viewName.$extension")
if (isset($viewPath) && ) {
file_exists("$viewPath$viewName.$extension")) {
include("$viewPath$viewName.$extension"); include("$viewPath$viewName.$extension");
return; return;
} }
include(ROOT_CORE."/Views/$viewName.$extension"); include(ROOT_CORE . "/Views/$viewName.$extension");
} }
/** /**
* Función que "renderiza" las vistas * Función que "renderiza" las vistas
* *
* @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
* @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/". * 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. * @param string $extension (opcional) Extensión del archivo.
* *
* @return void * @return void
@ -52,29 +53,28 @@ 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(
$viewName, $viewName,
$viewPath, $viewPath,
@ -86,17 +86,17 @@ 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");
$this->include($viewName, $viewPath, $extension); $this->include($viewName, $viewPath, $extension);
} }
@ -105,17 +105,17 @@ 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");
$this->include($viewName, $viewPath, $extension); $this->include($viewName, $viewPath, $extension);
} }
@ -153,12 +153,12 @@ 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 SITE_URL.substr($path,1); return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
}
return $path; return $path;
} }
} }
?>