Add missing docblocks and return types.

This commit is contained in:
kj 2023-03-25 12:26:42 -04:00
parent 1bde430251
commit 3c8a21161f
4 changed files with 64 additions and 29 deletions

View File

@ -132,8 +132,9 @@ class Model {
/**
* Reinicia la configuración de la sentencia SQL.
* @return void
*/
protected static function resetQuery() {
protected static function resetQuery(): void {
static::$querySelect = [
'select' => ['*'],
'where' => '',
@ -282,8 +283,9 @@ class Model {
/**
* Actualiza los valores en la BD con los valores del objeto actual.
* @return void
*/
protected function update() {
protected function update(): void {
$atts = $this->getVars();
foreach ($atts as $key => $value) {
@ -310,8 +312,9 @@ class Model {
/**
* Inserta una nueva fila en la base de datos a partir del
* objeto actual.
* @return void
*/
protected function add() {
protected function add(): void {
$db = static::db();
$atts = $this->getVars();
@ -334,8 +337,9 @@ class Model {
/**
* Revisa si el objeto a guardar es nuevo o no y según el resultado
* llama a update para actualizar o add para insertar una nueva fila.
* @return void
*/
public function save() {
public function save(): void {
$pk = static::$primaryKey;
if (isset($this->$pk))
$this->update();
@ -345,8 +349,9 @@ class Model {
/**
* Elimina el objeto actual de la base de datos.
* @return void
*/
public function delete() {
public function delete(): void {
$table = static::table();
$pk = static::$primaryKey;
$sql = "DELETE FROM $table WHERE $pk=:$pk";

View File

@ -19,11 +19,23 @@
namespace Libs;
class Neuron {
/**
* __construct
*
* @param object|array $data
*/
public function __construct(array|object $data = []) {
foreach($data as $key => $value)
$this->{$key} = $value;
}
/**
* __get
*
* @param string $index
* @return mixed
*/
public function __get(string $index) {
return (isset($this->{$index}) &&
$this->{$index} != '') ? $this->{$index} : null;

View File

@ -19,16 +19,25 @@ class Router {
private static $put = [];
private static $delete = [];
private static $last;
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
public static function defaultNotFound () {
/**
* Función callback por defectio para cuando
* no se encuentra configurada la ruta.
*
* @return 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>';
}
/**
* __construct
*/
private function __construct() {}
/*
/**
* Parsea para deectar las pseudovariables (ej: {variable})
*
* @param string $path
@ -42,7 +51,7 @@ 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, $callback) : array {
private static function parse(string $path, $callback): array {
preg_match_all('/{(\w+)}/s', $path, $matches, PREG_PATTERN_ORDER);
$paramNames = $matches[1];
@ -64,7 +73,7 @@ class Router {
}
/*
/**
* Devuelve el ruta base o raiz del proyecto sobre la que trabajará el router.
*
* Ej: Si la url del sistema está en "https://ejemplo.com/duckbrain"
@ -72,13 +81,13 @@ 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);
}
/*
/**
* Redirije a una ruta relativa interna.
*
* @param string $path
@ -87,8 +96,9 @@ class Router {
* Ej: Si nuesto sistema está en "https://ejemplo.com/duckbrain"
* llamamos a Router::redirect('/docs'), entonces seremos
* redirigidos a "https://ejemplo.com/duckbrain/docs".
* @return void
*/
public static function redirect(string $path) {
public static function redirect(string $path): void {
header('Location: '.static::basePath().substr($path,1));
}
@ -103,7 +113,7 @@ class Router {
* Devuelve un enlace estático.
*/
public static function middleware($callback, int $priority = null) : Router {
public static function middleware($callback, int $priority = null): Router {
if (!isset(static::$last))
return new static();
@ -138,7 +148,7 @@ class Router {
* json - Donde se encuentran los valores JSON enviados en el body.
*
*/
private static function getReq() : Neuron {
private static function getReq(): Neuron {
$req = new Neuron();
$req->get = new Neuron($_GET);
$req->post = new Neuron($_POST);
@ -152,7 +162,7 @@ class Router {
* @return object
* Devuelve un objeto con los datos recibidos en JSON.
*/
private static function get_json() : object {
private static function get_json(): object {
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
return json_decode(trim(file_get_contents("php://input")));
@ -172,7 +182,7 @@ class Router {
* @return Router
* Devuelve un enlace estático.
*/
public static function get(string $path, $callback) {
public static function get(string $path, $callback): Router {
static::$get[] = static::parse($path, $callback);
static::$last = ['get', count(static::$get)-1];
return new static();
@ -190,7 +200,7 @@ class Router {
* @return Router
* Devuelve un enlace estático.
*/
public static function post(string $path, $callback) : Router {
public static function post(string $path, $callback): Router {
static::$post[] = static::parse($path, $callback);
static::$last = ['post', count(static::$post)-1];
return new static();
@ -209,7 +219,7 @@ class Router {
* Devuelve un enlace estático
*/
public static function put(string $path, $callback) : Router {
public static function put(string $path, $callback): Router {
static::$put[] = static::parse($path, $callback);
static::$last = ['put', count(static::$put)-1];
return new static();
@ -227,7 +237,7 @@ class Router {
* @return static
* Devuelve un enlace estático
*/
public static function delete(string $path, $callback) : Router {
public static function delete(string $path, $callback): Router {
static::$delete[] = static::parse($path, $callback);
static::$last = ['delete', count(static::$delete)-1];
return new static();
@ -261,8 +271,9 @@ class Router {
* $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
*/
public static function apply() {
public static function apply(): void {
$path = static::currentPath();
$routers = [];
switch ($_SERVER['REQUEST_METHOD']){ // Según el método selecciona un arreglo de routers configurados

View File

@ -24,8 +24,10 @@ class View extends Neuron {
*
* @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/".
*
* @return void
*/
public static function render(string $viewName, array $params = [], string $viewPath = null) {
public static function render(string $viewName, array $params = [], string $viewPath = null): void {
$instance = new View($params);
$instance->html($viewName, $viewPath);
}
@ -37,13 +39,16 @@ class View extends Neuron {
* 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/".
* (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/".
* @return void
*/
public function html(string $viewName, string $viewPath = null) {
public function html(string $viewName, string $viewPath = null): void {
$view = $this;
if (isset($viewPath) && file_exists($viewPath.$viewName.'.php'))
return include($viewPath.$viewName.'.php');
if (isset($viewPath) && file_exists($viewPath.$viewName.'.php')) {
include($viewPath.$viewName.'.php');
return;
}
include(ROOT_DIR.'/src/Views/'.$viewName.'.php');
}
@ -51,9 +56,10 @@ class View extends Neuron {
/**
* Imprime los datos en Json.
*
* @param object $data
* @param object|array $data
* @return void
*/
public function json(object $data) {
public function json(object|array $data): void {
header('Content-Type: application/json; charset=utf-8');
print(json_encode($data));
}
@ -62,8 +68,9 @@ class View extends Neuron {
* Imprime los datos en texto plano
*
* @param string $txt
* @return void
*/
public function text(string $txt) {
public function text(string $txt): void {
header('Content-Type: text/plain; charset=utf-8');
print($txt);
}