Reorganize code for PSR and others code prettify.

This commit is contained in:
KJ 2024-05-09 15:13:52 -04:00
parent 6a1085b224
commit f5f803dde2
7 changed files with 191 additions and 67 deletions

View File

@ -30,7 +30,8 @@ class Database extends PDO {
* *
* @return PDO * @return PDO
*/ */
static public function getInstance() : PDO { static public function getInstance(): PDO
{
if (is_null(self::$db)) { if (is_null(self::$db)) {
if (DB_TYPE == 'sqlite') { if (DB_TYPE == 'sqlite') {
@ -43,7 +44,6 @@ class Database extends PDO {
try { try {
self::$db = new PDO($dsn, DB_USER, DB_PASS); self::$db = new PDO($dsn, DB_USER, DB_PASS);
} catch (PDOException $e) { } catch (PDOException $e) {
echo "<pre>";
throw new Exception( throw new Exception(
'Error at connect to database: ' . $e->getMessage() 'Error at connect to database: ' . $e->getMessage()
); );

View File

@ -20,7 +20,8 @@ class Middleware {
* *
* @return mixed * @return mixed
*/ */
public static function next(Neuron $req): mixed { public static function next(Neuron $req): mixed
{
$next = array_pop($req->next); $next = array_pop($req->next);
return call_user_func_array($next, [$req]); return call_user_func_array($next, [$req]);
} }

View File

@ -49,7 +49,8 @@ class Model {
* *
* @return PDO * @return PDO
*/ */
protected static function db() : PDO { protected static function db(): PDO
{
if (is_null(static::$db)) if (is_null(static::$db))
static::$db = Database::getInstance(); static::$db = Database::getInstance();
@ -62,7 +63,8 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function beginTransaction() : bool { public function beginTransaction(): bool
{
return static::db()->beginTransaction(); return static::db()->beginTransaction();
} }
@ -72,7 +74,8 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function rollBack() : bool { public function rollBack(): bool
{
return static::db()->rollBack(); return static::db()->rollBack();
} }
@ -82,7 +85,8 @@ class Model {
* *
* @return bool * @return bool
*/ */
public function commit() : bool { public function commit(): bool
{
return static::db()->commit(); return static::db()->commit();
} }
@ -103,7 +107,8 @@ class Model {
* @return array * @return array
* Contiene el resultado de la llamada SQL . * Contiene el resultado de la llamada SQL .
*/ */
protected static function query(string $query, bool $resetQuery = true) : array { protected static function query(string $query, bool $resetQuery = true): array
{
$db = static::db(); $db = static::db();
try { try {
@ -136,7 +141,8 @@ class Model {
* Reinicia la configuración de la sentencia SQL. * Reinicia la configuración de la sentencia SQL.
* @return void * @return void
*/ */
protected static function resetQuery(): void { protected static function resetQuery(): void
{
static::$querySelect = [ static::$querySelect = [
'select' => ['*'], 'select' => ['*'],
'where' => '', 'where' => '',
@ -158,7 +164,8 @@ class Model {
* @return string * @return string
* Contiene la sentencia SQL. * Contiene la sentencia SQL.
*/ */
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'] != '')
@ -201,7 +208,8 @@ class Model {
* @return string * @return string
* Parámetro de sustitución. * Parámetro de sustitución.
*/ */
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;
@ -217,7 +225,8 @@ class Model {
* @return static * @return static
* Retorna un objeto de la clase actual. * Retorna un objeto de la clase actual.
*/ */
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;
@ -237,7 +246,8 @@ class Model {
* @return array * @return array
* Contiene los atributos indexados del objeto actual. * Contiene los atributos indexados del objeto actual.
*/ */
protected function getVars() : array { protected function getVars(): array
{
$reflection = new ReflectionClass($this); $reflection = new ReflectionClass($this);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC); $properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$result = []; $result = [];
@ -266,7 +276,8 @@ class Model {
* @return string * @return string
* Devuelve el nombre de la clase actual. * Devuelve el nombre de la clase actual.
*/ */
public static function className() : string { public static function className(): string
{
return strtolower(substr(strrchr(get_called_class(), '\\'), 1)); return strtolower(substr(strrchr(get_called_class(), '\\'), 1));
} }
@ -277,7 +288,8 @@ class Model {
* *
* @return string * @return string
*/ */
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::className().static::$tableSufix;
@ -287,7 +299,8 @@ class Model {
* Actualiza los valores en la BD con los valores del objeto actual. * Actualiza los valores en la BD con los valores del objeto actual.
* @return void * @return void
*/ */
protected function update(): void { protected function update(): void
{
$atts = $this->getVars(); $atts = $this->getVars();
foreach ($atts as $key => $value) { foreach ($atts as $key => $value) {
@ -316,7 +329,8 @@ class Model {
* objeto actual. * objeto actual.
* @return void * @return void
*/ */
protected function add(): void { protected function add(): void
{
$db = static::db(); $db = static::db();
$atts = $this->getVars(); $atts = $this->getVars();
@ -341,7 +355,8 @@ class Model {
* llama a update para actualizar o add para insertar una nueva fila. * llama a update para actualizar o add para insertar una nueva fila.
* @return void * @return void
*/ */
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();
@ -370,7 +385,8 @@ class Model {
* *
* @return static * @return static
*/ */
public static function select(array $columns) : static { public static function select(array $columns): static
{
static::$querySelect['select'] = $columns; static::$querySelect['select'] = $columns;
return new static(); return new static();
@ -384,7 +400,8 @@ class Model {
* *
* @return static * @return static
*/ */
public static function from(array $tables) : static { public static function from(array $tables): static
{
static::$querySelect['from'] = join(', ', $tables); static::$querySelect['from'] = join(', ', $tables);
return new static(); return new static();
@ -408,8 +425,19 @@ class Model {
* *
* @return static * @return static
*/ */
public static function where(string $column, string $operatorOrValue, string $value=null, bool $no_filter = false) : static { public static function where(
return static::and($column, $operatorOrValue, $value, $no_filter); string $column,
string $operatorOrValue,
string $value = null,
bool $no_filter = false
): static
{
return static::and(
$column,
$operatorOrValue,
$value,
$no_filter
);
} }
/** /**
@ -430,7 +458,13 @@ class Model {
* *
* @return static * @return static
*/ */
public static function and(string $column, string $operatorOrValue, string $value=null, bool $no_filter = false) : static { public static function and(
string $column,
string $operatorOrValue,
string $value = null,
bool $no_filter = false
): static
{
if (is_null($value)) { if (is_null($value)) {
$value = $operatorOrValue; $value = $operatorOrValue;
$operatorOrValue = '='; $operatorOrValue = '=';
@ -465,7 +499,13 @@ class Model {
* *
* @return static * @return static
*/ */
public static function or(string $column, string $operatorOrValue, string $value=null, bool $no_filter = false) : static { public static function or(
string $column,
string $operatorOrValue,
string $value = null,
bool $no_filter = false
): static
{
if (is_null($value)) { if (is_null($value)) {
$value = $operatorOrValue; $value = $operatorOrValue;
$operatorOrValue = '='; $operatorOrValue = '=';
@ -496,7 +536,12 @@ class Model {
* *
* @return static * @return static
*/ */
public static function where_in(string $column, array $arr, bool $in = true) : static { public static function where_in(
string $column,
array $arr,
bool $in = true
): static
{
$arrIn = []; $arrIn = [];
foreach($arr as $value) { foreach($arr as $value) {
$arrIn[] = static::bindValue($value); $arrIn[] = static::bindValue($value);
@ -527,7 +572,13 @@ class Model {
* *
* @return static * @return static
*/ */
public static function leftJoin(string $table, string $columnA, string $operatorOrColumnB, string $columnB = null) : static { public static function leftJoin(
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
if (is_null($columnB)) { if (is_null($columnB)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -555,7 +606,13 @@ class Model {
* *
* @return static * @return static
*/ */
public static function rightJoin(string $table, string $columnA, string $operatorOrColumnB, string $columnB = null) : static { public static function rightJoin(
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
if (is_null($columnB)) { if (is_null($columnB)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -583,7 +640,13 @@ class Model {
* *
* @return static * @return static
*/ */
public static function innerJoin(string $table, string $columnA, string $operatorOrColumnB, string $columnB = null) : static { public static function innerJoin(
string $table,
string $columnA,
string $operatorOrColumnB,
string $columnB = null
): static
{
if (is_null($columnB)) { if (is_null($columnB)) {
$columnB = $operatorOrColumnB; $columnB = $operatorOrColumnB;
$operatorOrColumnB = '='; $operatorOrColumnB = '=';
@ -602,7 +665,8 @@ class Model {
* *
* @return static * @return static
*/ */
public static function groupBy(array $arr) : static { public static function groupBy(array $arr): static
{
static::$querySelect['groupBy'] = join(', ', $arr); static::$querySelect['groupBy'] = join(', ', $arr);
return new static(); return new static();
} }
@ -618,7 +682,8 @@ class Model {
* *
* @return static * @return static
*/ */
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
@ -639,7 +704,8 @@ class Model {
* *
* @return static * @return static
*/ */
public static function orderBy(string $value, string $order = 'ASC') : static { public static function orderBy(string $value, string $order = 'ASC'): static
{
if ($value == "RAND") { if ($value == "RAND") {
static::$querySelect['orderBy'] = 'RAND()'; static::$querySelect['orderBy'] = 'RAND()';
return new static(); return new static();
@ -665,7 +731,8 @@ class Model {
* *
* @return int * @return int
*/ */
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'],
@ -707,7 +774,8 @@ class Model {
* *
* @return static|null * @return static|null
*/ */
public static function getById(mixed $id): ?static { public static function getById(mixed $id): ?static
{
return static::where(static::$primaryKey, $id)->getFirst(); return static::where(static::$primaryKey, $id)->getFirst();
} }
@ -722,7 +790,8 @@ class Model {
* *
* @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());
@ -756,9 +825,10 @@ 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 array * @return array
* Contiene un arreglo de instancias de la clase actual. * Arreglo con instancias del la clase actual resultantes del query.
*/ */
public static function get(bool $resetQuery = true) : array { // Devuelve array vacío si no encuentra nada. public static function get(bool $resetQuery = true): array
{
$sql = static::buildQuery(); $sql = static::buildQuery();
$result = static::query($sql, $resetQuery); $result = static::query($sql, $resetQuery);
@ -780,7 +850,8 @@ class Model {
* @return static|null * @return static|null
* Puede retornar un objeto static o null. * Puede retornar un objeto static o null.
*/ */
public static function getFirst(bool $resetQuery = true): ?static { // Devuelve null si no encuentra nada. public static function getFirst(bool $resetQuery = true): ?static
{
static::limit(1); static::limit(1);
$instances = static::get($resetQuery); $instances = static::get($resetQuery);
return empty($instances) ? null : $instances[0]; return empty($instances) ? null : $instances[0];
@ -792,7 +863,8 @@ class Model {
* @return array * @return array
* 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);
@ -813,7 +885,8 @@ class Model {
* *
* @return void * @return void
*/ */
public function setNull(string|array $atts): void { public function setNull(string|array $atts): void
{
if (is_array($atts)) { if (is_array($atts)) {
foreach ($atts as $att) foreach ($atts as $att)
if (!in_array($att, $this->toNull)) if (!in_array($att, $this->toNull))

View File

@ -27,7 +27,8 @@ class Neuron {
* *
* @param array $data * @param array $data
*/ */
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]) ||
@ -42,9 +43,10 @@ class Neuron {
* __get * __get
* *
* @param string $index * @param string $index
* @return mixed * @return null
*/ */
public function __get(string $index) : mixed { public function __get(string $index): null
{
return null; return null;
} }
} }

View File

@ -39,7 +39,8 @@ class Request extends Neuron {
* *
* @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(string $path = '/')
{
$this->path = $path; $this->path = $path;
$this->get = new Neuron($_GET); $this->get = new Neuron($_GET);
$this->post = new Neuron($_POST); $this->post = new Neuron($_POST);

View File

@ -28,7 +28,8 @@ 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>';
} }
@ -52,7 +53,8 @@ class Router {
* path - Contiene la ruta con las pseudovariables reeplazadas por expresiones regulares. * path - Contiene la ruta con las pseudovariables reeplazadas por expresiones regulares.
* callback - Contiene el callback en formato Namespace\Clase::Método. * callback - Contiene el callback en formato Namespace\Clase::Método.
*/ */
private static function parse(string $path, callable $callback): array { private static function parse(string $path, callable $callback): array
{
preg_match_all('/{(\w+)}/s', $path, $matches, PREG_PATTERN_ORDER); preg_match_all('/{(\w+)}/s', $path, $matches, PREG_PATTERN_ORDER);
$paramNames = $matches[1]; $paramNames = $matches[1];
@ -78,7 +80,8 @@ class Router {
* *
* @return string * @return string
*/ */
public static function basePath(): string { public static function basePath(): string
{
if (defined('SITE_URL')) if (defined('SITE_URL'))
return parse_url(SITE_URL, PHP_URL_PATH); return parse_url(SITE_URL, PHP_URL_PATH);
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR); return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
@ -95,7 +98,8 @@ class Router {
* redirigidos a "https://ejemplo.com/duckbrain/docs". * redirigidos a "https://ejemplo.com/duckbrain/docs".
* @return void * @return void
*/ */
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().substr($path,1));
exit; exit;
} }
@ -110,7 +114,8 @@ 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();
@ -140,7 +145,8 @@ class Router {
* *
* @return static * @return static
*/ */
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();
@ -168,7 +174,8 @@ class Router {
* @return * @return
* Devuelve la instancia actual. * Devuelve la instancia actual.
*/ */
public static function configure(string $method, string $path, ?callable $callback = null): static { public static function configure(string $method, string $path, ?callable $callback = null): static
{
if (is_null($callback)) { if (is_null($callback)) {
$path = preg_quote($path, '/'); $path = preg_quote($path, '/');
$path = preg_replace( $path = preg_replace(
@ -201,7 +208,8 @@ class Router {
* @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);
} }
@ -216,8 +224,9 @@ class Router {
* @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);
} }
/** /**
@ -232,7 +241,8 @@ class Router {
* 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);
} }
@ -247,7 +257,8 @@ class Router {
* @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);
} }
@ -262,7 +273,8 @@ class Router {
* @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);
} }
@ -271,7 +283,8 @@ 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('/'.preg_quote(static::basePath(), '/').'/',
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1); '/', strtok($_SERVER['REQUEST_URI'], '?'), 1);
} }
@ -296,7 +309,8 @@ class Router {
* Si no la ruta no coincide con ninguna de las rutas configuradas, ejecutará el callback $notFoundCallback * 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(): void
{
$path = static::currentPath(); $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 configurados
'POST' => static::$post, 'POST' => static::$post,

View File

@ -22,10 +22,16 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
private function include(string $viewName, string $viewPath = null, string $extension = 'php'): void { private function include(
string $viewName,
string $viewPath = null,
string $extension = 'php'
): void
{
$view = $this; $view = $this;
if (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;
} }
@ -43,7 +49,13 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public static function render(string $viewName, array|Neuron $params = [], string $viewPath = null, string $extension = 'php'): void { public static function render(
string $viewName,
array|Neuron $params = [],
string $viewPath = null,
string $extension = 'php'
): void
{
$instance = new View($params); $instance = new View($params);
$instance->html($viewName, $viewPath); $instance->html($viewName, $viewPath);
} }
@ -57,8 +69,17 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public function html(string $viewName, string $viewPath = null, string $extension = 'php'): void { public function html(
$this->include($viewName, $viewPath, $extension); string $viewName,
string $viewPath = null,
string $extension = 'php'
): void
{
$this->include(
$viewName,
$viewPath,
$extension
);
} }
/** /**
@ -70,7 +91,12 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public function css(string $viewName, string $viewPath = null, string $extension = 'css'): void { public function css(
string $viewName,
string $viewPath = null,
string $extension = 'css'
): void
{
header("Content-type: text/css"); header("Content-type: text/css");
$this->include($viewName, $viewPath, $extension); $this->include($viewName, $viewPath, $extension);
} }
@ -84,7 +110,12 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public function js(string $viewName, string $viewPath = null, string $extension = 'js'): void { public function js(
string $viewName,
string $viewPath = null,
string $extension = 'js'
): void
{
header("Content-type: application/javascript"); header("Content-type: application/javascript");
$this->include($viewName, $viewPath, $extension); $this->include($viewName, $viewPath, $extension);
} }
@ -96,7 +127,8 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public function json(object|array $data): void { public function json(object|array $data): void
{
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
print(json_encode($data)); print(json_encode($data));
} }
@ -108,7 +140,8 @@ class View extends Neuron {
* *
* @return void * @return void
*/ */
public function text(string $txt): void { public function text(string $txt): void
{
header('Content-Type: text/plain; charset=utf-8'); header('Content-Type: text/plain; charset=utf-8');
print($txt); print($txt);
} }