Compare commits

..

No commits in common. "11141a0eee989b1d38aed4856250b989e4d92d8c" and "1bde430251619d4a832374d103bb7c50b7cf3e0a" have entirely different histories.

4 changed files with 34 additions and 77 deletions

View File

@ -132,9 +132,8 @@ class Model {
/** /**
* Reinicia la configuración de la sentencia SQL. * Reinicia la configuración de la sentencia SQL.
* @return void
*/ */
protected static function resetQuery(): void { protected static function resetQuery() {
static::$querySelect = [ static::$querySelect = [
'select' => ['*'], 'select' => ['*'],
'where' => '', 'where' => '',
@ -283,9 +282,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
*/ */
protected function update(): void { protected function update() {
$atts = $this->getVars(); $atts = $this->getVars();
foreach ($atts as $key => $value) { foreach ($atts as $key => $value) {
@ -312,9 +310,8 @@ class Model {
/** /**
* Inserta una nueva fila en la base de datos a partir del * Inserta una nueva fila en la base de datos a partir del
* objeto actual. * objeto actual.
* @return void
*/ */
protected function add(): void { protected function add() {
$db = static::db(); $db = static::db();
$atts = $this->getVars(); $atts = $this->getVars();
@ -337,9 +334,8 @@ class Model {
/** /**
* Revisa si el objeto a guardar es nuevo o no y según el resultado * 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. * llama a update para actualizar o add para insertar una nueva fila.
* @return void
*/ */
public function save(): void { public function save() {
$pk = static::$primaryKey; $pk = static::$primaryKey;
if (isset($this->$pk)) if (isset($this->$pk))
$this->update(); $this->update();
@ -349,9 +345,8 @@ class Model {
/** /**
* Elimina el objeto actual de la base de datos. * Elimina el objeto actual de la base de datos.
* @return void
*/ */
public function delete(): void { public function delete() {
$table = static::table(); $table = static::table();
$pk = static::$primaryKey; $pk = static::$primaryKey;
$sql = "DELETE FROM $table WHERE $pk=:$pk"; $sql = "DELETE FROM $table WHERE $pk=:$pk";
@ -805,21 +800,13 @@ class Model {
* Permite definir como nulo el valor de un atributo. * Permite definir como nulo el valor de un atributo.
* Sólo funciona para actualizar un elemento de la BD, no para insertar. * Sólo funciona para actualizar un elemento de la BD, no para insertar.
* *
* @param string|array $atts * @param array $atts
* Atributo o arreglo de atributos que se definirán como nulos.
*
* @return void
*/ */
public function setNull(string|array $atts): void { public function setNull(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)) $this->toNull[] = $att;
$this->toNull[] = $att;
return;
} }
if (!in_array($atts, $this->toNull))
$this->toNull[] = $atts;
} }
} }
?> ?>

View File

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

View File

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

View File

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