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.
* @return void
*/
protected static function resetQuery(): void {
protected static function resetQuery() {
static::$querySelect = [
'select' => ['*'],
'where' => '',
@ -283,9 +282,8 @@ class Model {
/**
* Actualiza los valores en la BD con los valores del objeto actual.
* @return void
*/
protected function update(): void {
protected function update() {
$atts = $this->getVars();
foreach ($atts as $key => $value) {
@ -312,9 +310,8 @@ class Model {
/**
* Inserta una nueva fila en la base de datos a partir del
* objeto actual.
* @return void
*/
protected function add(): void {
protected function add() {
$db = static::db();
$atts = $this->getVars();
@ -337,9 +334,8 @@ 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(): void {
public function save() {
$pk = static::$primaryKey;
if (isset($this->$pk))
$this->update();
@ -349,9 +345,8 @@ class Model {
/**
* Elimina el objeto actual de la base de datos.
* @return void
*/
public function delete(): void {
public function delete() {
$table = static::table();
$pk = static::$primaryKey;
$sql = "DELETE FROM $table WHERE $pk=:$pk";
@ -805,21 +800,13 @@ 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
* Atributo o arreglo de atributos que se definirán como nulos.
*
* @return void
* @param array $atts
*/
public function setNull(string|array $atts): void {
if (is_array($atts)) {
foreach ($atts as $att)
if (!in_array($att, $this->toNull))
$this->toNull[] = $att;
return;
public function setNull(array $atts) {
foreach ($atts as $att) {
if (!in_array($att, $this->toNull))
$this->toNull[] = $att;
}
if (!in_array($atts, $this->toNull))
$this->toNull[] = $atts;
}
}
?>

View File

@ -19,23 +19,11 @@
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,25 +19,16 @@ class Router {
private static $put = [];
private static $delete = [];
private static $last;
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
/**
* Función callback por defectio para cuando
* no se encuentra configurada la ruta.
*
* @return void
*/
public static function defaultNotFound (): void {
public static function defaultNotFound () {
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
@ -51,7 +42,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];
@ -73,7 +64,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"
@ -81,13 +72,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
@ -96,9 +87,8 @@ 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): void {
public static function redirect(string $path) {
header('Location: '.static::basePath().substr($path,1));
}
@ -113,7 +103,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();
@ -148,7 +138,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);
@ -162,7 +152,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")));
@ -182,7 +172,7 @@ class Router {
* @return Router
* 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::$last = ['get', count(static::$get)-1];
return new static();
@ -200,7 +190,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();
@ -219,7 +209,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();
@ -237,7 +227,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();
@ -271,9 +261,8 @@ 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(): void {
public static function apply() {
$path = static::currentPath();
$routers = [];
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
* (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->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
*
* @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
* (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/".
*/
public function html(string $viewName, string $viewPath = null): void {
public function html(string $viewName, string $viewPath = null) {
$view = $this;
if (isset($viewPath) && file_exists($viewPath.$viewName.'.php')) {
include($viewPath.$viewName.'.php');
return;
}
if (isset($viewPath) && file_exists($viewPath.$viewName.'.php'))
return include($viewPath.$viewName.'.php');
include(ROOT_DIR.'/src/Views/'.$viewName.'.php');
}
@ -56,10 +51,9 @@ class View extends Neuron {
/**
* Imprime los datos en Json.
*
* @param object|array $data
* @return void
* @param object $data
*/
public function json(object|array $data): void {
public function json(object $data) {
header('Content-Type: application/json; charset=utf-8');
print(json_encode($data));
}
@ -68,9 +62,8 @@ class View extends Neuron {
* Imprime los datos en texto plano
*
* @param string $txt
* @return void
*/
public function text(string $txt): void {
public function text(string $txt) {
header('Content-Type: text/plain; charset=utf-8');
print($txt);
}