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

View File

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

View File

@ -49,7 +49,8 @@ class Model {
*
* @return PDO
*/
protected static function db() : PDO {
protected static function db(): PDO
{
if (is_null(static::$db))
static::$db = Database::getInstance();
@ -62,7 +63,8 @@ class Model {
*
* @return bool
*/
public function beginTransaction() : bool {
public function beginTransaction(): bool
{
return static::db()->beginTransaction();
}
@ -72,7 +74,8 @@ class Model {
*
* @return bool
*/
public function rollBack() : bool {
public function rollBack(): bool
{
return static::db()->rollBack();
}
@ -82,7 +85,8 @@ class Model {
*
* @return bool
*/
public function commit() : bool {
public function commit(): bool
{
return static::db()->commit();
}
@ -103,7 +107,8 @@ class Model {
* @return array
* 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();
try {
@ -136,7 +141,8 @@ class Model {
* Reinicia la configuración de la sentencia SQL.
* @return void
*/
protected static function resetQuery(): void {
protected static function resetQuery(): void
{
static::$querySelect = [
'select' => ['*'],
'where' => '',
@ -158,7 +164,8 @@ class Model {
* @return string
* Contiene la sentencia SQL.
*/
protected static function buildQuery() : string {
protected static function buildQuery(): string
{
$sql = 'SELECT '.join(', ', static::$querySelect['select']);
if (static::$querySelect['from'] != '')
@ -201,7 +208,8 @@ class Model {
* @return string
* Parámetro de sustitución.
*/
private static function bindValue(string $value) : string{
private static function bindValue(string $value): string
{
$index = ':v_'.count(static::$queryVars);
static::$queryVars[$index] = $value;
return $index;
@ -217,7 +225,8 @@ class Model {
* @return static
* 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();
$instance = new $class;
@ -237,7 +246,8 @@ class Model {
* @return array
* Contiene los atributos indexados del objeto actual.
*/
protected function getVars() : array {
protected function getVars(): array
{
$reflection = new ReflectionClass($this);
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
$result = [];
@ -266,7 +276,8 @@ class Model {
* @return string
* 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));
}
@ -277,7 +288,8 @@ class Model {
*
* @return string
*/
protected static function table() : string {
protected static function table(): string
{
if (isset(static::$table))
return static::$table;
return static::className().static::$tableSufix;
@ -287,7 +299,8 @@ class Model {
* Actualiza los valores en la BD con los valores del objeto actual.
* @return void
*/
protected function update(): void {
protected function update(): void
{
$atts = $this->getVars();
foreach ($atts as $key => $value) {
@ -316,7 +329,8 @@ class Model {
* objeto actual.
* @return void
*/
protected function add(): void {
protected function add(): void
{
$db = static::db();
$atts = $this->getVars();
@ -341,7 +355,8 @@ class Model {
* llama a update para actualizar o add para insertar una nueva fila.
* @return void
*/
public function save(): void {
public function save(): void
{
$pk = static::$primaryKey;
if (isset($this->$pk))
$this->update();
@ -370,7 +385,8 @@ class Model {
*
* @return static
*/
public static function select(array $columns) : static {
public static function select(array $columns): static
{
static::$querySelect['select'] = $columns;
return new static();
@ -384,7 +400,8 @@ class Model {
*
* @return static
*/
public static function from(array $tables) : static {
public static function from(array $tables): static
{
static::$querySelect['from'] = join(', ', $tables);
return new static();
@ -408,8 +425,19 @@ class Model {
*
* @return static
*/
public static function where(string $column, string $operatorOrValue, string $value=null, bool $no_filter = false) : static {
return static::and($column, $operatorOrValue, $value, $no_filter);
public static function where(
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
*/
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)) {
$value = $operatorOrValue;
$operatorOrValue = '=';
@ -465,7 +499,13 @@ class Model {
*
* @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)) {
$value = $operatorOrValue;
$operatorOrValue = '=';
@ -496,7 +536,12 @@ class Model {
*
* @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 = [];
foreach($arr as $value) {
$arrIn[] = static::bindValue($value);
@ -527,7 +572,13 @@ class Model {
*
* @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)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -555,7 +606,13 @@ class Model {
*
* @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)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -583,7 +640,13 @@ class Model {
*
* @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)) {
$columnB = $operatorOrColumnB;
$operatorOrColumnB = '=';
@ -602,7 +665,8 @@ class Model {
*
* @return static
*/
public static function groupBy(array $arr) : static {
public static function groupBy(array $arr): static
{
static::$querySelect['groupBy'] = join(', ', $arr);
return new static();
}
@ -618,7 +682,8 @@ class Model {
*
* @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))
static::$querySelect['limit'] = $offsetOrQuantity;
else
@ -639,7 +704,8 @@ class Model {
*
* @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") {
static::$querySelect['orderBy'] = 'RAND()';
return new static();
@ -665,7 +731,8 @@ class Model {
*
* @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)
$backup = [
'select' => static::$querySelect['select'],
@ -707,7 +774,8 @@ class Model {
*
* @return static|null
*/
public static function getById(mixed $id): ?static {
public static function getById(mixed $id): ?static
{
return static::where(static::$primaryKey, $id)->getFirst();
}
@ -722,7 +790,8 @@ class Model {
*
* @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();
$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).
*
* @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();
$result = static::query($sql, $resetQuery);
@ -780,7 +850,8 @@ class Model {
* @return static|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);
$instances = static::get($resetQuery);
return empty($instances) ? null : $instances[0];
@ -792,7 +863,8 @@ class Model {
* @return array
* Contiene un arreglo de instancias de la clase actual.
*/
public static function all() : array {
public static function all(): array
{
$sql = 'SELECT * FROM '.static::table();
$result = static::query($sql);
@ -813,7 +885,8 @@ class Model {
*
* @return void
*/
public function setNull(string|array $atts): void {
public function setNull(string|array $atts): void
{
if (is_array($atts)) {
foreach ($atts as $att)
if (!in_array($att, $this->toNull))

View File

@ -27,7 +27,8 @@ class Neuron {
*
* @param array $data
*/
public function __construct(...$data) {
public function __construct(...$data)
{
if (count($data) === 1 &&
isset($data[0]) &&
(is_array($data[0]) ||
@ -42,9 +43,10 @@ class Neuron {
* __get
*
* @param string $index
* @return mixed
* @return null
*/
public function __get(string $index) : mixed {
public function __get(string $index): 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.
*/
public function __construct(string $path = '/') {
public function __construct(string $path = '/')
{
$this->path = $path;
$this->get = new Neuron($_GET);
$this->post = new Neuron($_POST);

View File

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

View File

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