Compare commits

..

10 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
10 changed files with 538 additions and 433 deletions

View File

@ -1,4 +1,5 @@
<?php
// Configuración de la base de datos
define('DB_TYPE', 'mysql');
define('DB_HOST', 'localhost');
@ -11,4 +12,4 @@ define('SITE_URL', '');
// Configuración avanzada
define('ROOT_DIR', __DIR__);
define('ROOT_CORE', ROOT_DIR.'/src');
define('ROOT_CORE', ROOT_DIR . '/src');

View File

@ -1,21 +1,23 @@
<?php
require_once('config.php');
// Incluir clases
spl_autoload_register(function ($className) {
$fp = str_replace('\\','/',$className);
$fp = str_replace('\\', '/', $className);
$name = basename($fp);
$dir = dirname($fp);
$file = ROOT_CORE.'/'.$dir.'/'.$name.'.php';
if (file_exists($file))
$file = ROOT_CORE . '/' . $dir . '/' . $name . '.php';
if (file_exists($file)) {
require_once $file;
}
});
// Incluir routers
$routers = glob(ROOT_CORE.'/Routers/*.php');
$routers = glob(ROOT_CORE . '/Routers/*.php');
foreach($routers as $file)
foreach ($routers as $file) {
require_once($file);
}
\Libs\Router::apply();
?>

View File

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

View File

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

View File

@ -1,4 +1,14 @@
<?php
namespace Libs;
use AllowDynamicProperties;
use Exception;
use PDO;
use PDOException;
use ReflectionClass;
use ReflectionProperty;
/**
* Model - DuckBrain
*
@ -10,29 +20,16 @@
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
use Libs\Database;
use PDO;
use PDOException;
use Exception;
use ReflectionClass;
use ReflectionProperty;
use AllowDynamicProperties;
#[AllowDynamicProperties]
class Model {
public ?int $id = null;
class Model
{
protected array $toNull = [];
static protected string $primaryKey = 'id';
static protected array $ignoreSave = ['id'];
static protected array $forceSave = [];
static protected string $table;
static protected string $tableSufix = 's';
static protected array $queryVars = [];
static protected array $querySelect = [
protected static string $primaryKey = 'id';
protected static array $ignoreSave = ['id'];
protected static array $forceSave = [];
protected static string $table;
protected static array $queryVars = [];
protected static array $querySelect = [
'select' => ['*'],
'where' => '',
'from' => '',
@ -41,7 +38,7 @@ class Model {
'innerJoin' => '',
'orderBy' => '',
'groupBy' => '',
'limit' => ''
'limit' => '',
];
/**
@ -51,12 +48,12 @@ class Model {
*/
protected static function db(): PDO
{
if (DB_TYPE == 'sqlite')
if (DB_TYPE == 'sqlite') {
return Database::getInstance(
type: DB_TYPE,
name: DB_NAME
);
else
} else {
return Database::getInstance(
DB_TYPE,
DB_HOST,
@ -65,6 +62,7 @@ class Model {
DB_PASS
);
}
}
/**
* Ejecuta PDO::beginTransaction para iniciar una transacción.
@ -72,7 +70,7 @@ class Model {
*
* @return bool
*/
public function beginTransaction(): bool
public static function beginTransaction(): bool
{
return static::db()->beginTransaction();
}
@ -83,13 +81,14 @@ class Model {
*
* @return bool
*/
public function rollBack(): bool
public static function rollBack(): bool
{
if ( static::db()->inTransaction())
if (static::db()->inTransaction()) {
return static::db()->rollBack();
else
} else {
return true;
}
}
/**
* Ejecuta PDO::commit para consignar una transacción.
@ -97,13 +96,14 @@ class Model {
*
* @return bool
*/
public function commit(): bool
public static function commit(): bool
{
if (static::db()->inTransaction())
if (static::db()->inTransaction()) {
return static::db()->commit();
else
} else {
return true;
}
}
/**
* Ejecuta una sentencia SQL en la base de datos.
@ -130,8 +130,9 @@ class Model {
$prepared = $db->prepare($query);
$prepared->execute(static::$queryVars);
} catch (PDOException $e) {
if ($db->inTransaction())
if ($db->inTransaction()) {
$db->rollBack();
}
$vars = json_encode(static::$queryVars);
@ -145,8 +146,9 @@ class Model {
$result = $prepared->fetchAll();
if ($resetQuery)
if ($resetQuery) {
static::resetQuery();
}
return $result;
}
@ -166,7 +168,7 @@ class Model {
'innerJoin' => '',
'orderBy' => '',
'groupBy' => '',
'limit' => ''
'limit' => '',
];
static::$queryVars = [];
}
@ -180,33 +182,41 @@ class Model {
*/
protected static function buildQuery(): string
{
$sql = 'SELECT '.join(', ', static::$querySelect['select']);
$sql = 'SELECT ' . join(', ', static::$querySelect['select']);
if (static::$querySelect['from'] != '')
$sql .= ' FROM '.static::$querySelect['from'];
else
$sql .= ' FROM '.static::table();
if (static::$querySelect['from'] != '') {
$sql .= ' FROM ' . static::$querySelect['from'];
} else {
$sql .= ' FROM ' . static::table();
}
if(static::$querySelect['innerJoin'] != '')
if (static::$querySelect['innerJoin'] != '') {
$sql .= static::$querySelect['innerJoin'];
}
if (static::$querySelect['leftJoin'] != '')
if (static::$querySelect['leftJoin'] != '') {
$sql .= static::$querySelect['leftJoin'];
}
if(static::$querySelect['rightJoin'] != '')
if (static::$querySelect['rightJoin'] != '') {
$sql .= static::$querySelect['rightJoin'];
}
if (static::$querySelect['where'] != '')
$sql .= ' WHERE '.static::$querySelect['where'];
if (static::$querySelect['where'] != '') {
$sql .= ' WHERE ' . static::$querySelect['where'];
}
if (static::$querySelect['groupBy'] != '')
$sql .= ' GROUP BY '.static::$querySelect['groupBy'];
if (static::$querySelect['groupBy'] != '') {
$sql .= ' GROUP BY ' . static::$querySelect['groupBy'];
}
if (static::$querySelect['orderBy'] != '')
$sql .= ' ORDER BY '.static::$querySelect['orderBy'];
if (static::$querySelect['orderBy'] != '') {
$sql .= ' ORDER BY ' . static::$querySelect['orderBy'];
}
if (static::$querySelect['limit'] != '')
$sql .= ' LIMIT '.static::$querySelect['limit'];
if (static::$querySelect['limit'] != '') {
$sql .= ' LIMIT ' . static::$querySelect['limit'];
}
return $sql;
}
@ -224,7 +234,7 @@ class Model {
*/
private static function bindValue(string $value): string
{
$index = ':v_'.count(static::$queryVars);
$index = ':v_' . count(static::$queryVars);
static::$queryVars[$index] = $value;
return $index;
}
@ -242,17 +252,24 @@ class Model {
protected static function getInstance(array $elem = []): static
{
$class = get_called_class();
$instance = new $class;
$instance = new $class();
$reflection = new ReflectionClass($instance);
$properties = $reflection->getProperties();
$propertyNames = array_column($properties, 'name');
$propertyNames = array_map(function ($property) {
return static::camelCaseToSnakeCase($property->name);
}, $properties);
foreach ($elem as $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;
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;
@ -273,23 +290,26 @@ class Model {
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$result = [];
foreach($properties as $property)
$result[$property->name] = isset($this->{$property->name})
foreach ($properties as $property) {
if (!in_array($property->name, static::$ignoreSave)) {
$result[$this->camelCaseToSnakeCase($property->name)] = isset($this->{$property->name})
? $this->{$property->name} : null;
}
}
foreach (static::$ignoreSave as $del)
unset($result[$del]);
foreach (static::$forceSave as $value)
foreach (static::$forceSave as $value) {
$result[$value] = isset($this->$value)
? $this->$value: null;
? $this->$value : null;
}
foreach ($result as $i => $property) {
if (gettype($property) == 'boolean')
if (gettype($property) == 'boolean') {
$result[$i] = $property ? '1' : '0';
}
if ($property instanceof \UnitEnum)
$result[$i] = $property->value;
if ($property instanceof \UnitEnum) {
$result[$i] = $property->value ?? $property->name;
}
}
return $result;
@ -299,12 +319,13 @@ class Model {
* Devuelve el nombre de la clase actual aunque sea una clase extendida.
*
* @return string
* Devuelve el nombre de la clase actual.
*
*/
public static function className(): string
{
return substr(
strrchr(get_called_class(), '\\'), 1
strrchr(get_called_class(), '\\'),
1
);
}
@ -317,15 +338,43 @@ class Model {
*/
protected static function table(): string
{
if (isset(static::$table))
if (isset(static::$table)) {
return static::$table;
}
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',
static::className()
'/(?<!^)[A-Z]/',
'_$0',
$string
)
).static::$tableSufix;
);
}
/**
* 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);
}
/**
@ -338,22 +387,23 @@ class Model {
foreach ($atts as $key => $value) {
if (isset($value)) {
if (in_array($key, $this->toNull))
$set[]="$key=NULL";
else {
$set[]="$key=:$key";
static::$queryVars[':'.$key] = $value;
if (in_array($key, $this->toNull)) {
$set[] = "$key=NULL";
} else {
$set[] = "$key=:$key";
static::$queryVars[':' . $key] = $value;
}
} else {
if (in_array($key, $this->toNull))
$set[]="$key=NULL";
if (in_array($key, $this->toNull)) {
$set[] = "$key=NULL";
}
}
}
$table = static::table();
$pk = static::$primaryKey;
$pkv = $this->$pk;
$sql = "UPDATE $table SET ".join(', ', $set)." WHERE $pk='$pkv'";
$sql = "UPDATE $table SET " . join(', ', $set) . " WHERE $pk='$pkv'";
static::query($sql);
}
@ -376,7 +426,7 @@ class Model {
}
$table = static::table();
$sql = "INSERT INTO $table (".join(', ', $into).") VALUES (".join(', ', $values).")";
$sql = "INSERT INTO $table (" . join(', ', $into) . ") VALUES (" . join(', ', $values) . ")";
static::query($sql);
$pk = static::$primaryKey;
@ -391,17 +441,19 @@ class Model {
public function save(): void
{
$pk = static::$primaryKey;
if (isset($this->$pk))
if (isset($this->$pk)) {
$this->update();
else
} else {
$this->add();
}
}
/**
* Elimina el objeto actual de la base de datos.
* @return void
*/
public function delete(): void {
public function delete(): void
{
$table = static::table();
$pk = static::$primaryKey;
$sql = "DELETE FROM $table WHERE $pk=:$pk";
@ -418,7 +470,7 @@ class Model {
*
* @return static
*/
public static function select(array $columns): static
public static function select(...$columns): static
{
static::$querySelect['select'] = $columns;
@ -433,7 +485,7 @@ class Model {
*
* @return static
*/
public static function from(array $tables): static
public static function from(...$tables): static
{
static::$querySelect['from'] = join(', ', $tables);
@ -449,7 +501,7 @@ class Model {
* @param string $operatorOrValue
* 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.
*
* @param bool $no_filter
@ -461,10 +513,9 @@ class Model {
public static function where(
string $column,
string $operatorOrValue,
string $value = null,
?string $value = null,
bool $no_filter = false
): static
{
): static {
return static::and(
$column,
$operatorOrValue,
@ -482,7 +533,7 @@ class Model {
* @param string $operatorOrValue
* 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.
*
* @param bool $no_filter
@ -494,22 +545,23 @@ class Model {
public static function and(
string $column,
string $operatorOrValue,
string $value = null,
?string $value = null,
bool $no_filter = false
): static
{
): static {
if (is_null($value)) {
$value = $operatorOrValue;
$operatorOrValue = '=';
}
if (!$no_filter)
if (!$no_filter) {
$value = static::bindValue($value);
}
if (static::$querySelect['where'] == '')
if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = "$column $operatorOrValue $value";
else
} else {
static::$querySelect['where'] .= " AND $column $operatorOrValue $value";
}
return new static();
}
@ -523,7 +575,7 @@ class Model {
* @param string $operatorOrValue
* 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.
*
* @param bool $no_filter
@ -535,22 +587,23 @@ class Model {
public static function or(
string $column,
string $operatorOrValue,
string $value = null,
?string $value = null,
bool $no_filter = false
): static
{
): static {
if (is_null($value)) {
$value = $operatorOrValue;
$operatorOrValue = '=';
}
if (!$no_filter)
if (!$no_filter) {
$value = static::bindValue($value);
}
if (static::$querySelect['where'] == '')
if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = "$column $operatorOrValue $value";
else
} else {
static::$querySelect['where'] .= " OR $column $operatorOrValue $value";
}
return new static();
}
@ -569,26 +622,27 @@ class Model {
*
* @return static
*/
public static function where_in(
public static function whereIn(
string $column,
array $arr,
bool $in = true
): static
{
): static {
$arrIn = [];
foreach($arr as $value) {
foreach ($arr as $value) {
$arrIn[] = static::bindValue($value);
}
if ($in)
$where_in = "$column IN (".join(', ', $arrIn).")";
else
$where_in = "$column NOT IN (".join(', ', $arrIn).")";
if ($in) {
$where_in = "$column IN (" . join(', ', $arrIn) . ")";
} else {
$where_in = "$column NOT IN (" . join(', ', $arrIn) . ")";
}
if (static::$querySelect['where'] == '')
if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = $where_in;
else
} else {
static::$querySelect['where'] .= " AND $where_in";
}
return new static();
}
@ -603,9 +657,10 @@ class Model {
* Columna a comparar para hacer el join.
*
* @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.
*
* @return static
@ -614,9 +669,8 @@ class Model {
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
?string $columnB = null
): static {
if (is_null($columnB)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -637,9 +691,10 @@ class Model {
* Columna a comparar para hacer el join.
*
* @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.
*
* @return static
@ -648,9 +703,8 @@ class Model {
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
?string $columnB = null
): static {
if (is_null($columnB)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -671,9 +725,10 @@ class Model {
* Columna a comparar para hacer el join.
*
* @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.
*
* @return static
@ -682,9 +737,8 @@ class Model {
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
?string $columnB = null
): static {
if (is_null($columnB)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -722,10 +776,11 @@ class Model {
*/
public static function limit(int $offsetOrQuantity, ?int $quantity = null): static
{
if (is_null($quantity))
if (is_null($quantity)) {
static::$querySelect['limit'] = $offsetOrQuantity;
else
static::$querySelect['limit'] = $offsetOrQuantity.', '.$quantity;
} else {
static::$querySelect['limit'] = $offsetOrQuantity . ', ' . $quantity;
}
return new static();
}
@ -749,10 +804,11 @@ class Model {
return new static();
}
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC'))
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC')) {
$order = 'ASC';
}
static::$querySelect['orderBy'] = $value.' '.$order;
static::$querySelect['orderBy'] = $value . ' ' . $order;
return new static();
}
@ -771,22 +827,25 @@ class Model {
*/
public static function count(bool $resetQuery = true, bool $useLimit = false): int
{
if (!$resetQuery)
if (!$resetQuery) {
$backup = [
'select' => static::$querySelect['select'],
'limit' => static::$querySelect['limit'],
'orderBy' => static::$querySelect['orderBy']
'orderBy' => static::$querySelect['orderBy'],
];
}
if ($useLimit && static::$querySelect['limit'] != '') {
static::$querySelect['select'] = ['1'];
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);
$result = $queryResult[0]['quantity'];
} 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['orderBy'] = '';
@ -823,12 +882,12 @@ class Model {
* @param string $search
* Contenido a buscar.
*
* @param array $in
* @param array|null $in
* (opcional) Columnas en las que se va a buscar (null para buscar en todas).
*
* @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) {
$className = get_called_class();
@ -838,18 +897,22 @@ class Model {
$search = static::bindValue($search);
$where = [];
if (DB_TYPE == 'sqlite')
foreach($in as $row)
if (DB_TYPE == 'sqlite') {
foreach ($in as $row) {
$where[] = "$row LIKE '%' || $search || '%'";
else
foreach($in as $row)
}
} else {
foreach ($in as $row) {
$where[] = "$row LIKE CONCAT('%', $search, '%')";
}
}
if (static::$querySelect['where']=='')
if (static::$querySelect['where'] == '') {
static::$querySelect['where'] = join(' OR ', $where);
else
static::$querySelect['where'] = static::$querySelect['where'] .' AND ('.join(' OR ', $where).')';
} else {
static::$querySelect['where'] = static::$querySelect['where'] . ' AND (' . join(' OR ', $where) . ')';
}
return new static();
}
@ -901,13 +964,14 @@ class Model {
*/
public static function all(): array
{
$sql = 'SELECT * FROM '.static::table();
$sql = 'SELECT * FROM ' . static::table();
$result = static::query($sql);
$instances = [];
foreach ($result as $row)
foreach ($result as $row) {
$instances[] = static::getInstance($row);
}
return $instances;
}
@ -916,22 +980,24 @@ class Model {
* Permite definir como nulo el valor de un atributo.
* 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.
*
* @return void
*/
public function setNull(string|array $atts): void
public function setNull(...$attributes): void
{
if (is_array($atts)) {
foreach ($atts as $att)
if (!in_array($att, $this->toNull))
if (is_array($attributes)) {
foreach ($attributes as $att) {
if (!in_array($att, $this->toNull)) {
$this->toNull[] = $att;
}
}
return;
}
if (!in_array($atts, $this->toNull))
$this->toNull[] = $atts;
if (!in_array($attributes, $this->toNull)) {
$this->toNull[] = $attributes;
}
}
}
?>

View File

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

View File

@ -1,4 +1,7 @@
<?php
namespace Libs;
/**
* Request - DuckBrain
*
@ -9,10 +12,8 @@
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
class Request extends Neuron {
class Request extends Neuron
{
public Neuron $get;
public Neuron $post;
public Neuron $put;
@ -41,14 +42,19 @@ class Request extends Neuron {
$this->body = file_get_contents("php://input");
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json")
if ($contentType === "application/json") {
$this->json = new Neuron(
(object) json_decode(trim($this->body), false)
);
else {
} else {
$this->json = new Neuron();
if (in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE']) &&
preg_match('/^[^;?\/:@&=+$,]{1,255}[=]/', $this->body, $matches)) { // Con la expresión regular verificamos que sea un http query string válido y evitamos errores de memoria en caso de que el body tenga algo más grande que eso.
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);
}
@ -64,8 +70,9 @@ class Request extends Neuron {
*/
public function handle(): mixed
{
if ($this->validate())
if ($this->validate()) {
return Middleware::next($this);
}
return null;
}
@ -77,21 +84,23 @@ class Request extends Neuron {
*/
public function validate(): bool
{
$actual = match($_SERVER['REQUEST_METHOD']) {
$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))
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]))
if (isset(static::messages()[Validator::$lastFailed])) {
$error = static::messages()[Validator::$lastFailed];
else {
$error = 'Error: validation failed of '.preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
} else {
$error = 'Error: validation failed of ' . preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
}
static::onInvalid($error);
@ -103,7 +112,8 @@ class Request extends Neuron {
*
* @return array
*/
public function rules(): array {
public function rules(): array
{
return [];
}
@ -112,7 +122,8 @@ class Request extends Neuron {
*
* @return array
*/
public function paramRules(): array {
public function paramRules(): array
{
return [];
}
@ -121,7 +132,8 @@ class Request extends Neuron {
*
* @return array
*/
public function getRules(): array {
public function getRules(): array
{
return [];
}
@ -130,7 +142,8 @@ class Request extends Neuron {
*
* @return array
*/
public function messages(): array {
public function messages(): array
{
return [];
}

View File

@ -1,4 +1,7 @@
<?php
namespace Libs;
/**
* Router - DuckBrain
*
@ -10,10 +13,8 @@
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
class Router {
class Router
{
private static $get = [];
private static $post = [];
private static $put = [];
@ -28,7 +29,7 @@ class Router {
*
* @return void
*/
public static function defaultNotFound (): void
public static function defaultNotFound(): void
{
header("HTTP/1.0 404 Not Found");
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Página no encontrada</h2>';
@ -37,7 +38,9 @@ class Router {
/**
* __construct
*/
private function __construct() {}
private function __construct()
{
}
/**
* Parsea para deectar las pseudovariables (ej: {variable})
@ -62,12 +65,13 @@ class Router {
$path = preg_replace(
['/\\\{\w+\\\}/s'],
['([^\/]+)'],
$path);
$path
);
return [
'path' => $path,
'callback' => [$callback],
'paramNames' => $paramNames
'paramNames' => $paramNames,
];
}
@ -82,8 +86,9 @@ class Router {
*/
public static function basePath(): string
{
if (defined('SITE_URL') && !empty(SITE_URL))
return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/').'/';
if (defined('SITE_URL') && !empty(SITE_URL)) {
return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/') . '/';
}
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
}
@ -100,7 +105,7 @@ class Router {
*/
public static function redirect(string $path): void
{
header('Location: '.static::basePath().ltrim($path, '/'));
header('Location: ' . static::basePath() . ltrim($path, '/'));
exit;
}
@ -114,20 +119,22 @@ class Router {
* @return static
* Devuelve la instancia actual.
*/
public static function middleware(callable $callback, int $priority = null): static
public static function middleware(callable $callback, ?int $priority = null): static
{
if (!isset(static::$last))
if (!isset(static::$last)) {
return new static();
}
$method = static::$last[0];
$index = static::$last[1];
if (isset($priority) && $priority <= 0)
if (isset($priority) && $priority <= 0) {
$priority = 1;
}
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback']))
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback'])) {
static::$$method[$index]['callback'][] = $callback;
else {
} else {
static::$$method[$index]['callback'] = array_merge(
array_slice(static::$$method[$index]['callback'], 0, $priority),
[$callback],
@ -147,8 +154,9 @@ class Router {
*/
public static function reconfigure(callable $callback): static
{
if (empty(static::$last))
if (empty(static::$last)) {
return new static();
}
$method = static::$last[0];
$index = static::$last[1];
@ -181,19 +189,21 @@ class Router {
$path = preg_replace(
['/\\\{\w+\\\}/s'],
['([^\/]+)'],
$path);
$path
);
foreach(static::$$method as $index => $router)
foreach (static::$$method as $index => $router) {
if ($router['path'] == $path) {
static::$last = [$method, $index];
break;
}
}
return new static();
}
static::$$method[] = static::parse($path, $callback);
static::$last = [$method, count(static::$$method)-1];
static::$last = [$method, count(static::$$method) - 1];
return new static();
}
@ -202,13 +212,13 @@ class Router {
*
* @param string $path
* Ruta con pseudovariables.
* @param callable $callback
* @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida.
*
* @return static
* 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);
}
@ -218,13 +228,13 @@ class Router {
*
* @param string $path
* Ruta con pseudovariables.
* @param callable $callback
* @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida.
*
* @return static
* 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);
}
@ -234,14 +244,14 @@ class Router {
*
* @param string $path
* Ruta con pseudovariables.
* @param callable $callback
* @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida.
*
* @return static
* 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);
}
@ -251,13 +261,13 @@ class Router {
*
* @param string $path
* Ruta con pseudovariables.
* @param callable $callback
* @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida.
*
* @return static
* 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);
}
@ -267,13 +277,13 @@ class Router {
*
* @param string $path
* Ruta con pseudovariables
* @param callable $callback
* @param callable|null $callback
* Callback que será llamado cuando la ruta configurada en $path coincida.
*
* @return static
* Devuelve la instancia actual
*/
public static function delete(string $path, callable $callback = null): static
public static function delete(string $path, ?callable $callback = null): static
{
return static::configure('delete', $path, $callback);
}
@ -283,23 +293,27 @@ class Router {
*
* @return string
*/
public static function currentPath() : string
public static function currentPath(): string
{
return preg_replace('/'.preg_quote(static::basePath(), '/').'/',
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1);
return preg_replace(
'/' . preg_quote(static::basePath(), '/') . '/',
'/',
strtok($_SERVER['REQUEST_URI'], '?'),
1
);
}
/**
* Aplica 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
*/
public static function apply(string $path = null): void
public static function apply(?string $path = null): void
{
$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
'POST' => static::$post,
'PUT' => static::$put,
'PATCH' => static::$patch,
@ -308,7 +322,7 @@ class Router {
};
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]);
// Objtener un reflection del callback
@ -316,15 +330,17 @@ class Router {
if ($lastCallback instanceof \Closure) { // si es función anónima
$reflectionCallback = new \ReflectionFunction($lastCallback);
} else {
if (is_string($lastCallback))
if (is_string($lastCallback)) {
$lastCallback = preg_split('/::/', $lastCallback);
}
// Revisamos su es un método o solo una función
if (count($lastCallback) == 2)
if (count($lastCallback) == 2) {
$reflectionCallback = new \ReflectionMethod($lastCallback[0], $lastCallback[1]);
else
} else {
$reflectionCallback = new \ReflectionFunction($lastCallback[0]);
}
}
// Obtener los parámetros
$arguments = $reflectionCallback->getParameters();
@ -334,22 +350,23 @@ class Router {
// Verificamos si la clase está o no tipada
if (empty($argumentClass)) {
$request = new Request;
$request = new Request();
} else {
$request = new $argumentClass;
$request = new $argumentClass();
// Verificamos que sea instancia de Request (requerimiento)
if (!($request instanceof Request))
if (!($request instanceof Request)) {
throw new \Exception('Bad argument type on router callback.');
}
}
} else {
$request = new Request;
$request = new Request();
}
// Comprobando y guardando los parámetros variables de la ruta
if (isset($matches[1])) {
foreach ($matches as $index => $match) {
$paramName = $router['paramNames'][$index-1];
$paramName = $router['paramNames'][$index - 1];
$request->params->$paramName = urldecode($match[0]);
}
}
@ -369,6 +386,6 @@ class Router {
}
// Si no hay router que coincida llamamos a $notFoundCallBack
call_user_func_array(static::$notFoundCallback, [new Request]);
call_user_func_array(static::$notFoundCallback, [new Request()]);
}
}

View File

@ -1,4 +1,7 @@
<?php
namespace Libs;
/**
* Validator - DuckBrain
*
@ -28,10 +31,8 @@
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
class Validator {
class Validator
{
public static string $lastFailed = '';
/**
@ -47,9 +48,10 @@ class Validator {
foreach ($rulesList as $target => $rules) {
$rules = preg_split('/\|/', $rules);
foreach ($rules as $rule) {
if (static::checkRule($haystack->{$target}, $rule))
if (static::checkRule($haystack->{$target}, $rule)) {
continue;
static::$lastFailed = $target.'.'.$rule;
}
static::$lastFailed = $target . '.' . $rule;
return false;
}
}
@ -71,10 +73,11 @@ class Validator {
$rule = [static::class, $arguments[0]];
$arguments[0] = $subject;
if (is_callable($rule))
if (is_callable($rule)) {
return call_user_func_array($rule, $arguments);
}
throw new \Exception('Bad rule: "'.preg_split('/::/', $rule)[1].'"' );
throw new \Exception('Bad rule: "' . preg_split('/::/', $rule)[1] . '"');
}
/**

View File

@ -1,4 +1,7 @@
<?php
namespace Libs;
/**
* View - DuckBrain
*
@ -7,44 +10,42 @@
* @author KJ
* @website https://kj2.me
* @licence MIT
*/
namespace Libs;
class View extends Neuron {
*/
class View extends Neuron
{
/**
* Incluye el archivo.
*
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
* @param string $viewPath (opcional) Ruta donde se encuentra la vista.
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista.
* @param string $extension (opcional) Extensión del archivo.
*
* @return void
*/
protected function include(
string $viewName,
string $viewPath = null,
?string $viewPath = null,
string $extension = 'php'
): void
{
$view = $this;
if (isset($viewPath) &&
file_exists("$viewPath$viewName.$extension")) {
): void {
if (
isset($viewPath) &&
file_exists("$viewPath$viewName.$extension")
) {
include("$viewPath$viewName.$extension");
return;
}
include(ROOT_CORE."/Views/$viewName.$extension");
include(ROOT_CORE . "/Views/$viewName.$extension");
}
/**
* Función que "renderiza" las vistas
*
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista mediante $view ($param['index'] se usaría así: $view->index)
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista
* mediante $view ($param['index'] se usaría así: $view->index)
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que
* la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string $extension (opcional) Extensión del archivo.
*
* @return void
@ -52,29 +53,28 @@ class View extends Neuron {
public static function render(
string $viewName,
array|Neuron $params = [],
string $viewPath = null,
?string $viewPath = null,
string $extension = 'php'
): void
{
): void {
$instance = new View($params);
$instance->html($viewName, $viewPath);
$instance->html($viewName, $viewPath, $extension);
}
/**
* Renderiza las vistas HTML
*
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string $extension (opcional) Extensión del archivo.
*
* @return void
*/
public function html(
string $viewName,
string $viewPath = null,
?string $viewPath = null,
string $extension = 'php'
): void
{
): void {
$this->include(
$viewName,
$viewPath,
@ -86,17 +86,17 @@ class View extends Neuron {
* Renderiza código CSS.
*
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string $extension (opcional) Extensión del archivo.
*
* @return void
*/
public function css(
string $viewName,
string $viewPath = null,
?string $viewPath = null,
string $extension = 'css'
): void
{
): void {
header("Content-type: text/css");
$this->include($viewName, $viewPath, $extension);
}
@ -105,17 +105,17 @@ class View extends Neuron {
* Renderiza código Javascript.
*
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
* @param string $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string|null $viewPath (opcional) Ruta donde se encuentra la vista. En caso de que la vista no se
* encuentre en esa ruta, se usará la ruta por defecto "src/Views/".
* @param string $extension (opcional) Extensión del archivo.
*
* @return void
*/
public function js(
string $viewName,
string $viewPath = null,
?string $viewPath = null,
string $extension = 'js'
): void
{
): void {
header("Content-type: application/javascript");
$this->include($viewName, $viewPath, $extension);
}
@ -155,10 +155,10 @@ class View extends Neuron {
*/
public static function route(string $path = '/'): string
{
if (defined('SITE_URL') && !empty(SITE_URL))
return rtrim(SITE_URL, '/').'/'.ltrim($path, '/');
if (defined('SITE_URL') && !empty(SITE_URL)) {
return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
}
return $path;
}
}
?>