BREAKING CHANGE: Adhere to PSR-12 coding standards.
- Model: where_in method was renamed as whereIn.
This commit is contained in:
@ -1,4 +1,5 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
// Configuración de la base de datos
|
// Configuración de la base de datos
|
||||||
define('DB_TYPE', 'mysql');
|
define('DB_TYPE', 'mysql');
|
||||||
define('DB_HOST', 'localhost');
|
define('DB_HOST', 'localhost');
|
||||||
@ -11,4 +12,4 @@ define('SITE_URL', '');
|
|||||||
|
|
||||||
// Configuración avanzada
|
// Configuración avanzada
|
||||||
define('ROOT_DIR', __DIR__);
|
define('ROOT_DIR', __DIR__);
|
||||||
define('ROOT_CORE', ROOT_DIR.'/src');
|
define('ROOT_CORE', ROOT_DIR . '/src');
|
||||||
|
13
index.php
13
index.php
@ -1,20 +1,23 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
require_once('config.php');
|
require_once('config.php');
|
||||||
|
|
||||||
// Incluir clases
|
// Incluir clases
|
||||||
spl_autoload_register(function ($className) {
|
spl_autoload_register(function ($className) {
|
||||||
$fp = str_replace('\\','/',$className);
|
$fp = str_replace('\\', '/', $className);
|
||||||
$name = basename($fp);
|
$name = basename($fp);
|
||||||
$dir = dirname($fp);
|
$dir = dirname($fp);
|
||||||
$file = ROOT_CORE.'/'.$dir.'/'.$name.'.php';
|
$file = ROOT_CORE . '/' . $dir . '/' . $name . '.php';
|
||||||
if (file_exists($file))
|
if (file_exists($file)) {
|
||||||
require_once $file;
|
require_once $file;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Incluir routers
|
// Incluir routers
|
||||||
$routers = glob(ROOT_CORE.'/Routers/*.php');
|
$routers = glob(ROOT_CORE . '/Routers/*.php');
|
||||||
|
|
||||||
foreach($routers as $file)
|
foreach ($routers as $file) {
|
||||||
require_once($file);
|
require_once($file);
|
||||||
|
}
|
||||||
|
|
||||||
\Libs\Router::apply();
|
\Libs\Router::apply();
|
||||||
|
@ -1,4 +1,11 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use PDO;
|
||||||
|
use PDOException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Database - DuckBrain
|
* Database - DuckBrain
|
||||||
*
|
*
|
||||||
@ -8,38 +15,33 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class Database extends PDO
|
||||||
|
{
|
||||||
|
private static array $databases = [];
|
||||||
|
|
||||||
namespace Libs;
|
private function __construct()
|
||||||
|
{
|
||||||
use PDO;
|
}
|
||||||
use PDOException;
|
|
||||||
use Exception;
|
|
||||||
|
|
||||||
class Database extends PDO {
|
|
||||||
static private array $databases = [];
|
|
||||||
|
|
||||||
private function __construct() {}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
|
* Devuelve una instancia homogénea (singlenton) de la base de datos (PDO).
|
||||||
*
|
*
|
||||||
* @return PDO
|
* @return PDO
|
||||||
*/
|
*/
|
||||||
static public function getInstance(
|
public static function getInstance(
|
||||||
string $type = 'mysql',
|
string $type = 'mysql',
|
||||||
string $host = 'localhost',
|
string $host = 'localhost',
|
||||||
string $name = '',
|
string $name = '',
|
||||||
string $user = '',
|
string $user = '',
|
||||||
string $pass = '',
|
string $pass = '',
|
||||||
): PDO
|
): PDO {
|
||||||
{
|
$key = $type . '/' . $host . '/' . $name . '/' . $user;
|
||||||
$key = $type.'/'.$host.'/'.$name.'/'.$user;
|
|
||||||
if (empty(static::$databases[$key])) {
|
if (empty(static::$databases[$key])) {
|
||||||
|
|
||||||
if ($type == 'sqlite') {
|
if ($type == 'sqlite') {
|
||||||
$dsn = $type .':'. $name;
|
$dsn = $type . ':' . $name;
|
||||||
} else
|
} else {
|
||||||
$dsn = $type.':dbname='.$name.';host='.$host;
|
$dsn = $type . ':dbname=' . $name . ';host=' . $host;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
static::$databases[$key] = new PDO($dsn, $user, $pass);
|
static::$databases[$key] = new PDO($dsn, $user, $pass);
|
||||||
@ -55,4 +57,3 @@ class Database extends PDO {
|
|||||||
return static::$databases[$key];
|
return static::$databases[$key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
?>
|
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Middleware - DuckBrain
|
* Middleware - DuckBrain
|
||||||
*
|
*
|
||||||
@ -8,11 +11,8 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class Middleware
|
||||||
namespace Libs;
|
{
|
||||||
|
|
||||||
class Middleware {
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Llama al siguiente callback.
|
* Llama al siguiente callback.
|
||||||
*
|
*
|
||||||
|
@ -1,4 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
|
use AllowDynamicProperties;
|
||||||
|
use Exception;
|
||||||
|
use PDO;
|
||||||
|
use PDOException;
|
||||||
|
use ReflectionClass;
|
||||||
|
use ReflectionProperty;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Model - DuckBrain
|
* Model - DuckBrain
|
||||||
*
|
*
|
||||||
@ -10,27 +20,17 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Libs;
|
|
||||||
|
|
||||||
use Libs\Database;
|
|
||||||
use PDO;
|
|
||||||
use PDOException;
|
|
||||||
use Exception;
|
|
||||||
use ReflectionClass;
|
|
||||||
use ReflectionProperty;
|
|
||||||
use AllowDynamicProperties;
|
|
||||||
|
|
||||||
#[AllowDynamicProperties]
|
#[AllowDynamicProperties]
|
||||||
class Model {
|
class Model
|
||||||
protected array $toNull = [];
|
{
|
||||||
static protected string $primaryKey = 'id';
|
protected array $toNull = [];
|
||||||
static protected array $ignoreSave = ['id'];
|
protected static string $primaryKey = 'id';
|
||||||
static protected array $forceSave = [];
|
protected static array $ignoreSave = ['id'];
|
||||||
static protected string $table;
|
protected static array $forceSave = [];
|
||||||
static protected string $tableSufix = 's';
|
protected static string $table;
|
||||||
static protected array $queryVars = [];
|
protected static string $tableSufix = 's';
|
||||||
static protected array $querySelect = [
|
protected static array $queryVars = [];
|
||||||
|
protected static array $querySelect = [
|
||||||
'select' => ['*'],
|
'select' => ['*'],
|
||||||
'where' => '',
|
'where' => '',
|
||||||
'from' => '',
|
'from' => '',
|
||||||
@ -39,7 +39,7 @@ class Model {
|
|||||||
'innerJoin' => '',
|
'innerJoin' => '',
|
||||||
'orderBy' => '',
|
'orderBy' => '',
|
||||||
'groupBy' => '',
|
'groupBy' => '',
|
||||||
'limit' => ''
|
'limit' => '',
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -49,12 +49,12 @@ class Model {
|
|||||||
*/
|
*/
|
||||||
protected static function db(): PDO
|
protected static function db(): PDO
|
||||||
{
|
{
|
||||||
if (DB_TYPE == 'sqlite')
|
if (DB_TYPE == 'sqlite') {
|
||||||
return Database::getInstance(
|
return Database::getInstance(
|
||||||
type: DB_TYPE,
|
type: DB_TYPE,
|
||||||
name: DB_NAME
|
name: DB_NAME
|
||||||
);
|
);
|
||||||
else
|
} else {
|
||||||
return Database::getInstance(
|
return Database::getInstance(
|
||||||
DB_TYPE,
|
DB_TYPE,
|
||||||
DB_HOST,
|
DB_HOST,
|
||||||
@ -62,6 +62,7 @@ class Model {
|
|||||||
DB_USER,
|
DB_USER,
|
||||||
DB_PASS
|
DB_PASS
|
||||||
);
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -83,10 +84,11 @@ class Model {
|
|||||||
*/
|
*/
|
||||||
public static function rollBack(): bool
|
public static function rollBack(): bool
|
||||||
{
|
{
|
||||||
if ( static::db()->inTransaction())
|
if (static::db()->inTransaction()) {
|
||||||
return static::db()->rollBack();
|
return static::db()->rollBack();
|
||||||
else
|
} else {
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -97,28 +99,29 @@ class Model {
|
|||||||
*/
|
*/
|
||||||
public static function commit(): bool
|
public static function commit(): bool
|
||||||
{
|
{
|
||||||
if (static::db()->inTransaction())
|
if (static::db()->inTransaction()) {
|
||||||
return static::db()->commit();
|
return static::db()->commit();
|
||||||
else
|
} else {
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Ejecuta una sentencia SQL en la base de datos.
|
* Ejecuta una sentencia SQL en la base de datos.
|
||||||
*
|
*
|
||||||
* @param string $query
|
* @param string $query
|
||||||
* Contiene la sentencia SQL que se desea ejecutar.
|
* Contiene la sentencia SQL que se desea ejecutar.
|
||||||
*
|
*
|
||||||
* @throws Exception
|
* @throws Exception
|
||||||
* En caso de que la sentencia SQL falle, devolverá un error en
|
* En caso de que la sentencia SQL falle, devolverá un error en
|
||||||
* pantalla y hará rolllback en caso de estar dentro de una
|
* pantalla y hará rolllback en caso de estar dentro de una
|
||||||
* transacción (ver método beginTransacction).
|
* transacción (ver método beginTransacction).
|
||||||
*
|
*
|
||||||
* @param bool $resetQuery
|
* @param bool $resetQuery
|
||||||
* Indica si el query debe reiniciarse o no (por defecto es true).
|
* Indica si el query debe reiniciarse o no (por defecto es true).
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -128,8 +131,9 @@ class Model {
|
|||||||
$prepared = $db->prepare($query);
|
$prepared = $db->prepare($query);
|
||||||
$prepared->execute(static::$queryVars);
|
$prepared->execute(static::$queryVars);
|
||||||
} catch (PDOException $e) {
|
} catch (PDOException $e) {
|
||||||
if ($db->inTransaction())
|
if ($db->inTransaction()) {
|
||||||
$db->rollBack();
|
$db->rollBack();
|
||||||
|
}
|
||||||
|
|
||||||
$vars = json_encode(static::$queryVars);
|
$vars = json_encode(static::$queryVars);
|
||||||
|
|
||||||
@ -143,8 +147,9 @@ class Model {
|
|||||||
|
|
||||||
$result = $prepared->fetchAll();
|
$result = $prepared->fetchAll();
|
||||||
|
|
||||||
if ($resetQuery)
|
if ($resetQuery) {
|
||||||
static::resetQuery();
|
static::resetQuery();
|
||||||
|
}
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
}
|
}
|
||||||
@ -164,7 +169,7 @@ class Model {
|
|||||||
'innerJoin' => '',
|
'innerJoin' => '',
|
||||||
'orderBy' => '',
|
'orderBy' => '',
|
||||||
'groupBy' => '',
|
'groupBy' => '',
|
||||||
'limit' => ''
|
'limit' => '',
|
||||||
];
|
];
|
||||||
static::$queryVars = [];
|
static::$queryVars = [];
|
||||||
}
|
}
|
||||||
@ -174,37 +179,45 @@ class Model {
|
|||||||
* construída, llama a resetQuery.
|
* construída, llama a resetQuery.
|
||||||
*
|
*
|
||||||
* @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'] != '') {
|
||||||
$sql .= ' FROM '.static::$querySelect['from'];
|
$sql .= ' FROM ' . static::$querySelect['from'];
|
||||||
else
|
} else {
|
||||||
$sql .= ' FROM '.static::table();
|
$sql .= ' FROM ' . static::table();
|
||||||
|
}
|
||||||
|
|
||||||
if(static::$querySelect['innerJoin'] != '')
|
if (static::$querySelect['innerJoin'] != '') {
|
||||||
$sql .= static::$querySelect['innerJoin'];
|
$sql .= static::$querySelect['innerJoin'];
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['leftJoin'] != '')
|
if (static::$querySelect['leftJoin'] != '') {
|
||||||
$sql .= static::$querySelect['leftJoin'];
|
$sql .= static::$querySelect['leftJoin'];
|
||||||
|
}
|
||||||
|
|
||||||
if(static::$querySelect['rightJoin'] != '')
|
if (static::$querySelect['rightJoin'] != '') {
|
||||||
$sql .= static::$querySelect['rightJoin'];
|
$sql .= static::$querySelect['rightJoin'];
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['where'] != '')
|
if (static::$querySelect['where'] != '') {
|
||||||
$sql .= ' WHERE '.static::$querySelect['where'];
|
$sql .= ' WHERE ' . static::$querySelect['where'];
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['groupBy'] != '')
|
if (static::$querySelect['groupBy'] != '') {
|
||||||
$sql .= ' GROUP BY '.static::$querySelect['groupBy'];
|
$sql .= ' GROUP BY ' . static::$querySelect['groupBy'];
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['orderBy'] != '')
|
if (static::$querySelect['orderBy'] != '') {
|
||||||
$sql .= ' ORDER BY '.static::$querySelect['orderBy'];
|
$sql .= ' ORDER BY ' . static::$querySelect['orderBy'];
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['limit'] != '')
|
if (static::$querySelect['limit'] != '') {
|
||||||
$sql .= ' LIMIT '.static::$querySelect['limit'];
|
$sql .= ' LIMIT ' . static::$querySelect['limit'];
|
||||||
|
}
|
||||||
|
|
||||||
return $sql;
|
return $sql;
|
||||||
}
|
}
|
||||||
@ -215,14 +228,14 @@ class Model {
|
|||||||
* parámetro de sustitución y devuelve este último.
|
* parámetro de sustitución y devuelve este último.
|
||||||
*
|
*
|
||||||
* @param string $value
|
* @param string $value
|
||||||
* Valor a vincular.
|
* Valor a vincular.
|
||||||
*
|
*
|
||||||
* @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;
|
||||||
}
|
}
|
||||||
@ -231,26 +244,27 @@ class Model {
|
|||||||
* Crea una instancia del objeto actual a partir de un arreglo.
|
* Crea una instancia del objeto actual a partir de un arreglo.
|
||||||
*
|
*
|
||||||
* @param mixed $elem
|
* @param mixed $elem
|
||||||
* Puede recibir un arreglo o un objeto que contiene los valores
|
* Puede recibir un arreglo o un objeto que contiene los valores
|
||||||
* que tendrán sus atributos.
|
* que tendrán sus atributos.
|
||||||
*
|
*
|
||||||
* @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();
|
||||||
$reflection = new ReflectionClass($instance);
|
$reflection = new ReflectionClass($instance);
|
||||||
$properties = $reflection->getProperties();
|
$properties = $reflection->getProperties();
|
||||||
$propertyNames = array_column($properties, 'name');
|
$propertyNames = array_column($properties, 'name');
|
||||||
|
|
||||||
foreach ($elem as $key => $value) {
|
foreach ($elem as $key => $value) {
|
||||||
$index = array_search($key, $propertyNames);
|
$index = array_search($key, $propertyNames);
|
||||||
if (is_numeric($index) && enum_exists($properties[$index]->getType()->getName()))
|
if (is_numeric($index) && enum_exists($properties[$index]->getType()->getName())) {
|
||||||
$instance->$key = $properties[$index]->getType()->getName()::tryfrom($value);
|
$instance->$key = $properties[$index]->getType()->getName()::tryfrom($value);
|
||||||
else
|
} else {
|
||||||
$instance->$key = $value;
|
$instance->$key = $value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $instance;
|
return $instance;
|
||||||
@ -263,7 +277,7 @@ class Model {
|
|||||||
* que sean private o protected pero estén en static::$forceSave.
|
* que sean private o protected pero estén en static::$forceSave.
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -271,23 +285,28 @@ class Model {
|
|||||||
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
|
$properties = $reflection->getProperties(ReflectionProperty::IS_PUBLIC);
|
||||||
$result = [];
|
$result = [];
|
||||||
|
|
||||||
foreach($properties as $property)
|
foreach ($properties as $property) {
|
||||||
$result[$property->name] = isset($this->{$property->name})
|
$result[$property->name] = isset($this->{$property->name})
|
||||||
? $this->{$property->name} : null;
|
? $this->{$property->name} : null;
|
||||||
|
}
|
||||||
|
|
||||||
foreach (static::$ignoreSave as $del)
|
foreach (static::$ignoreSave as $del) {
|
||||||
unset($result[$del]);
|
unset($result[$del]);
|
||||||
|
}
|
||||||
|
|
||||||
foreach (static::$forceSave as $value)
|
foreach (static::$forceSave as $value) {
|
||||||
$result[$value] = isset($this->$value)
|
$result[$value] = isset($this->$value)
|
||||||
? $this->$value: null;
|
? $this->$value : null;
|
||||||
|
}
|
||||||
|
|
||||||
foreach ($result as $i => $property) {
|
foreach ($result as $i => $property) {
|
||||||
if (gettype($property) == 'boolean')
|
if (gettype($property) == 'boolean') {
|
||||||
$result[$i] = $property ? '1' : '0';
|
$result[$i] = $property ? '1' : '0';
|
||||||
|
}
|
||||||
|
|
||||||
if ($property instanceof \UnitEnum)
|
if ($property instanceof \UnitEnum) {
|
||||||
$result[$i] = $property->value;
|
$result[$i] = $property->value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return $result;
|
return $result;
|
||||||
@ -297,12 +316,13 @@ class Model {
|
|||||||
* Devuelve el nombre de la clase actual aunque sea una clase extendida.
|
* Devuelve el nombre de la clase actual aunque sea una clase extendida.
|
||||||
*
|
*
|
||||||
* @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 substr(
|
return substr(
|
||||||
strrchr(get_called_class(), '\\'), 1
|
strrchr(get_called_class(), '\\'),
|
||||||
|
1
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -315,15 +335,17 @@ class Model {
|
|||||||
*/
|
*/
|
||||||
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 strtolower(
|
return strtolower(
|
||||||
preg_replace(
|
preg_replace(
|
||||||
'/(?<!^)[A-Z]/', '_$0',
|
'/(?<!^)[A-Z]/',
|
||||||
|
'_$0',
|
||||||
static::className()
|
static::className()
|
||||||
)
|
)
|
||||||
).static::$tableSufix;
|
) . static::$tableSufix;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -336,22 +358,23 @@ class Model {
|
|||||||
|
|
||||||
foreach ($atts as $key => $value) {
|
foreach ($atts as $key => $value) {
|
||||||
if (isset($value)) {
|
if (isset($value)) {
|
||||||
if (in_array($key, $this->toNull))
|
if (in_array($key, $this->toNull)) {
|
||||||
$set[]="$key=NULL";
|
$set[] = "$key=NULL";
|
||||||
else {
|
} else {
|
||||||
$set[]="$key=:$key";
|
$set[] = "$key=:$key";
|
||||||
static::$queryVars[':'.$key] = $value;
|
static::$queryVars[':' . $key] = $value;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (in_array($key, $this->toNull))
|
if (in_array($key, $this->toNull)) {
|
||||||
$set[]="$key=NULL";
|
$set[] = "$key=NULL";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$table = static::table();
|
$table = static::table();
|
||||||
$pk = static::$primaryKey;
|
$pk = static::$primaryKey;
|
||||||
$pkv = $this->$pk;
|
$pkv = $this->$pk;
|
||||||
$sql = "UPDATE $table SET ".join(', ', $set)." WHERE $pk='$pkv'";
|
$sql = "UPDATE $table SET " . join(', ', $set) . " WHERE $pk='$pkv'";
|
||||||
static::query($sql);
|
static::query($sql);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -374,7 +397,7 @@ class Model {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$table = static::table();
|
$table = static::table();
|
||||||
$sql = "INSERT INTO $table (".join(', ', $into).") VALUES (".join(', ', $values).")";
|
$sql = "INSERT INTO $table (" . join(', ', $into) . ") VALUES (" . join(', ', $values) . ")";
|
||||||
static::query($sql);
|
static::query($sql);
|
||||||
|
|
||||||
$pk = static::$primaryKey;
|
$pk = static::$primaryKey;
|
||||||
@ -389,17 +412,19 @@ class Model {
|
|||||||
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();
|
||||||
else
|
} else {
|
||||||
$this->add();
|
$this->add();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Elimina el objeto actual de la base de datos.
|
* Elimina el objeto actual de la base de datos.
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function delete(): void {
|
public function delete(): void
|
||||||
|
{
|
||||||
$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";
|
||||||
@ -412,7 +437,7 @@ class Model {
|
|||||||
* Define SELECT en la sentencia SQL.
|
* Define SELECT en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param array $columns
|
* @param array $columns
|
||||||
* Columnas que se selecionarán en la consulta SQL.
|
* Columnas que se selecionarán en la consulta SQL.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
@ -427,7 +452,7 @@ class Model {
|
|||||||
* Define FROM en la sentencia SQL.
|
* Define FROM en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param array $tables
|
* @param array $tables
|
||||||
* Tablas que se selecionarán en la consulta SQL.
|
* Tablas que se selecionarán en la consulta SQL.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
@ -442,27 +467,26 @@ class Model {
|
|||||||
* Define el WHERE en la sentencia SQL.
|
* Define el WHERE en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $column
|
* @param string $column
|
||||||
* La columna a comparar.
|
* La columna a comparar.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrValue
|
* @param string $operatorOrValue
|
||||||
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $value
|
* @param string|null $value
|
||||||
* (opcional) El valor a comparar en la columna.
|
* (opcional) El valor a comparar en la columna.
|
||||||
*
|
*
|
||||||
* @param bool $no_filter
|
* @param bool $no_filter
|
||||||
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
||||||
* contra ataques SQLI (por defeco es false).
|
* contra ataques SQLI (por defeco es false).
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function where(
|
public static function where(
|
||||||
string $column,
|
string $column,
|
||||||
string $operatorOrValue,
|
string $operatorOrValue,
|
||||||
?string $value = null,
|
?string $value = null,
|
||||||
bool $no_filter = false
|
bool $no_filter = false
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
return static::and(
|
return static::and(
|
||||||
$column,
|
$column,
|
||||||
$operatorOrValue,
|
$operatorOrValue,
|
||||||
@ -475,39 +499,40 @@ class Model {
|
|||||||
* Define AND en la sentencia SQL (se puede anidar).
|
* Define AND en la sentencia SQL (se puede anidar).
|
||||||
*
|
*
|
||||||
* @param string $column
|
* @param string $column
|
||||||
* La columna a comparar.
|
* La columna a comparar.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrValue
|
* @param string $operatorOrValue
|
||||||
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $value
|
* @param string|null $value
|
||||||
* (opcional) El valor el valor a comparar en la columna.
|
* (opcional) El valor el valor a comparar en la columna.
|
||||||
*
|
*
|
||||||
* @param bool $no_filter
|
* @param bool $no_filter
|
||||||
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
||||||
* contra ataques SQLI (por defecto es false).
|
* contra ataques SQLI (por defecto es false).
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function and(
|
public static function and(
|
||||||
string $column,
|
string $column,
|
||||||
string $operatorOrValue,
|
string $operatorOrValue,
|
||||||
?string $value = null,
|
?string $value = null,
|
||||||
bool $no_filter = false
|
bool $no_filter = false
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
if (is_null($value)) {
|
if (is_null($value)) {
|
||||||
$value = $operatorOrValue;
|
$value = $operatorOrValue;
|
||||||
$operatorOrValue = '=';
|
$operatorOrValue = '=';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$no_filter)
|
if (!$no_filter) {
|
||||||
$value = static::bindValue($value);
|
$value = static::bindValue($value);
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['where'] == '')
|
if (static::$querySelect['where'] == '') {
|
||||||
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
||||||
else
|
} else {
|
||||||
static::$querySelect['where'] .= " AND $column $operatorOrValue $value";
|
static::$querySelect['where'] .= " AND $column $operatorOrValue $value";
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -516,39 +541,40 @@ class Model {
|
|||||||
* Define OR en la sentencia SQL (se puede anidar).
|
* Define OR en la sentencia SQL (se puede anidar).
|
||||||
*
|
*
|
||||||
* @param string $column
|
* @param string $column
|
||||||
* La columna a comparar.
|
* La columna a comparar.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrValue
|
* @param string $operatorOrValue
|
||||||
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
* El operador o el valor a comparar como igual en caso de que $value no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $value
|
* @param string|null $value
|
||||||
* (opcional) El valor el valor a comparar en la columna.
|
* (opcional) El valor el valor a comparar en la columna.
|
||||||
*
|
*
|
||||||
* @param bool $no_filter
|
* @param bool $no_filter
|
||||||
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
|
||||||
* contra ataques SQLI (por defecto es false).
|
* contra ataques SQLI (por defecto es false).
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function or(
|
public static function or(
|
||||||
string $column,
|
string $column,
|
||||||
string $operatorOrValue,
|
string $operatorOrValue,
|
||||||
?string $value = null,
|
?string $value = null,
|
||||||
bool $no_filter = false
|
bool $no_filter = false
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
if (is_null($value)) {
|
if (is_null($value)) {
|
||||||
$value = $operatorOrValue;
|
$value = $operatorOrValue;
|
||||||
$operatorOrValue = '=';
|
$operatorOrValue = '=';
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!$no_filter)
|
if (!$no_filter) {
|
||||||
$value = static::bindValue($value);
|
$value = static::bindValue($value);
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['where'] == '')
|
if (static::$querySelect['where'] == '') {
|
||||||
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
||||||
else
|
} else {
|
||||||
static::$querySelect['where'] .= " OR $column $operatorOrValue $value";
|
static::$querySelect['where'] .= " OR $column $operatorOrValue $value";
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -557,36 +583,37 @@ class Model {
|
|||||||
* Define WHERE usando IN en la sentencia SQL.
|
* Define WHERE usando IN en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $column
|
* @param string $column
|
||||||
* La columna a comparar.
|
* La columna a comparar.
|
||||||
*
|
*
|
||||||
* @param array $arr
|
* @param array $arr
|
||||||
* Arreglo con todos los valores a comparar con la columna.
|
* Arreglo con todos los valores a comparar con la columna.
|
||||||
*
|
*
|
||||||
* @param bool $in
|
* @param bool $in
|
||||||
* Define si se tienen que comprobar negativa o positivamente.
|
* Define si se tienen que comprobar negativa o positivamente.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function where_in(
|
public static function whereIn(
|
||||||
string $column,
|
string $column,
|
||||||
array $arr,
|
array $arr,
|
||||||
bool $in = true
|
bool $in = true
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
$arrIn = [];
|
$arrIn = [];
|
||||||
foreach($arr as $value) {
|
foreach ($arr as $value) {
|
||||||
$arrIn[] = static::bindValue($value);
|
$arrIn[] = static::bindValue($value);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($in)
|
if ($in) {
|
||||||
$where_in = "$column IN (".join(', ', $arrIn).")";
|
$where_in = "$column IN (" . join(', ', $arrIn) . ")";
|
||||||
else
|
} else {
|
||||||
$where_in = "$column NOT IN (".join(', ', $arrIn).")";
|
$where_in = "$column NOT IN (" . join(', ', $arrIn) . ")";
|
||||||
|
}
|
||||||
|
|
||||||
if (static::$querySelect['where'] == '')
|
if (static::$querySelect['where'] == '') {
|
||||||
static::$querySelect['where'] = $where_in;
|
static::$querySelect['where'] = $where_in;
|
||||||
else
|
} else {
|
||||||
static::$querySelect['where'] .= " AND $where_in";
|
static::$querySelect['where'] .= " AND $where_in";
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -595,26 +622,26 @@ class Model {
|
|||||||
* Define LEFT JOIN en la sentencia SQL.
|
* Define LEFT JOIN en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $table
|
* @param string $table
|
||||||
* Tabla que se va a juntar a la del objeto actual.
|
* Tabla que se va a juntar a la del objeto actual.
|
||||||
*
|
*
|
||||||
* @param string $columnA
|
* @param string $columnA
|
||||||
* Columna a comparar para hacer el join.
|
* Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrColumnB
|
* @param string $operatorOrColumnB
|
||||||
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
|
* Operador o columna a comparar como igual para hacer
|
||||||
|
* el join en caso de que $columnB no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $columnB
|
* @param string|null $columnB
|
||||||
* (opcional) Columna a comparar para hacer el join.
|
* (opcional) Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function leftJoin(
|
public static function leftJoin(
|
||||||
string $table,
|
string $table,
|
||||||
string $columnA,
|
string $columnA,
|
||||||
string $operatorOrColumnB,
|
string $operatorOrColumnB,
|
||||||
?string $columnB = null
|
?string $columnB = null
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
if (is_null($columnB)) {
|
if (is_null($columnB)) {
|
||||||
$columnB = $operatorOrColumnB;
|
$columnB = $operatorOrColumnB;
|
||||||
$operatorOrColumnB = '=';
|
$operatorOrColumnB = '=';
|
||||||
@ -629,26 +656,26 @@ class Model {
|
|||||||
* Define RIGHT JOIN en la sentencia SQL.
|
* Define RIGHT JOIN en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $table
|
* @param string $table
|
||||||
* Tabla que se va a juntar a la del objeto actual.
|
* Tabla que se va a juntar a la del objeto actual.
|
||||||
*
|
*
|
||||||
* @param string $columnA
|
* @param string $columnA
|
||||||
* Columna a comparar para hacer el join.
|
* Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrColumnB
|
* @param string $operatorOrColumnB
|
||||||
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
|
* Operador o columna a comparar como igual para hacer
|
||||||
|
* el join en caso de que $columnB no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $columnB
|
* @param string|null $columnB
|
||||||
* (opcional) Columna a comparar para hacer el join.
|
* (opcional) Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function rightJoin(
|
public static function rightJoin(
|
||||||
string $table,
|
string $table,
|
||||||
string $columnA,
|
string $columnA,
|
||||||
string $operatorOrColumnB,
|
string $operatorOrColumnB,
|
||||||
?string $columnB = null
|
?string $columnB = null
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
if (is_null($columnB)) {
|
if (is_null($columnB)) {
|
||||||
$columnB = $operatorOrColumnB;
|
$columnB = $operatorOrColumnB;
|
||||||
$operatorOrColumnB = '=';
|
$operatorOrColumnB = '=';
|
||||||
@ -663,26 +690,26 @@ class Model {
|
|||||||
* Define INNER JOIN en la sentencia SQL.
|
* Define INNER JOIN en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $table
|
* @param string $table
|
||||||
* Tabla que se va a juntar a la del objeto actual.
|
* Tabla que se va a juntar a la del objeto actual.
|
||||||
*
|
*
|
||||||
* @param string $columnA
|
* @param string $columnA
|
||||||
* Columna a comparar para hacer el join.
|
* Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @param string $operatorOrColumnB
|
* @param string $operatorOrColumnB
|
||||||
* Operador o columna a comparar como igual para hacer el join en caso de que $columnB no se defina.
|
* Operador o columna a comparar como igual para hacer
|
||||||
|
* el join en caso de que $columnB no se defina.
|
||||||
*
|
*
|
||||||
* @param string|null $columnB
|
* @param string|null $columnB
|
||||||
* (opcional) Columna a comparar para hacer el join.
|
* (opcional) Columna a comparar para hacer el join.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
public static function innerJoin(
|
public static function innerJoin(
|
||||||
string $table,
|
string $table,
|
||||||
string $columnA,
|
string $columnA,
|
||||||
string $operatorOrColumnB,
|
string $operatorOrColumnB,
|
||||||
?string $columnB = null
|
?string $columnB = null
|
||||||
): static
|
): static {
|
||||||
{
|
|
||||||
if (is_null($columnB)) {
|
if (is_null($columnB)) {
|
||||||
$columnB = $operatorOrColumnB;
|
$columnB = $operatorOrColumnB;
|
||||||
$operatorOrColumnB = '=';
|
$operatorOrColumnB = '=';
|
||||||
@ -697,7 +724,7 @@ class Model {
|
|||||||
* Define GROUP BY en la sentencia SQL.
|
* Define GROUP BY en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param array $arr
|
* @param array $arr
|
||||||
* Columnas por las que se agrupará.
|
* Columnas por las que se agrupará.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
@ -711,19 +738,20 @@ class Model {
|
|||||||
* Define LIMIT en la sentencia SQL.
|
* Define LIMIT en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param int $offsetOrQuantity
|
* @param int $offsetOrQuantity
|
||||||
* Define el las filas a ignorar o la cantidad a tomar en
|
* Define el las filas a ignorar o la cantidad a tomar en
|
||||||
* caso de que $quantity no esté definido.
|
* caso de que $quantity no esté definido.
|
||||||
* @param int $quantity
|
* @param int $quantity
|
||||||
* Define la cantidad máxima de filas a tomar.
|
* Define la cantidad máxima de filas a tomar.
|
||||||
*
|
*
|
||||||
* @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 {
|
||||||
static::$querySelect['limit'] = $offsetOrQuantity.', '.$quantity;
|
static::$querySelect['limit'] = $offsetOrQuantity . ', ' . $quantity;
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -732,11 +760,11 @@ class Model {
|
|||||||
* Define ORDER BY en la sentencia SQL.
|
* Define ORDER BY en la sentencia SQL.
|
||||||
*
|
*
|
||||||
* @param string $value
|
* @param string $value
|
||||||
* Columna por la que se ordenará.
|
* Columna por la que se ordenará.
|
||||||
*
|
*
|
||||||
* @param string $order
|
* @param string $order
|
||||||
* (opcional) Define si el orden será de manera ascendente (ASC),
|
* (opcional) Define si el orden será de manera ascendente (ASC),
|
||||||
* descendente (DESC) o aleatorio (RAND).
|
* descendente (DESC) o aleatorio (RAND).
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
@ -747,10 +775,11 @@ class Model {
|
|||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC'))
|
if (!(strtoupper($order) == 'ASC' || strtoupper($order) == 'DESC')) {
|
||||||
$order = 'ASC';
|
$order = 'ASC';
|
||||||
|
}
|
||||||
|
|
||||||
static::$querySelect['orderBy'] = $value.' '.$order;
|
static::$querySelect['orderBy'] = $value . ' ' . $order;
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -759,32 +788,35 @@ class Model {
|
|||||||
* Retorna la cantidad de filas que hay en un query.
|
* Retorna la cantidad de filas que hay en un query.
|
||||||
*
|
*
|
||||||
* @param bool $resetQuery
|
* @param bool $resetQuery
|
||||||
* (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).
|
||||||
*
|
*
|
||||||
* @param bool $useLimit
|
* @param bool $useLimit
|
||||||
* (opcional) Permite usar limit para estabecer un máximo inical y final para contar.
|
* (opcional) Permite usar limit para estabecer un máximo inical y final para contar.
|
||||||
* Requiere que se haya definido antes el límite (por defecto en false).
|
* Requiere que se haya definido antes el límite (por defecto en false).
|
||||||
*
|
*
|
||||||
* @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'],
|
||||||
'limit' => static::$querySelect['limit'],
|
'limit' => static::$querySelect['limit'],
|
||||||
'orderBy' => static::$querySelect['orderBy']
|
'orderBy' => static::$querySelect['orderBy'],
|
||||||
];
|
];
|
||||||
|
}
|
||||||
|
|
||||||
if ($useLimit && static::$querySelect['limit'] != '') {
|
if ($useLimit && static::$querySelect['limit'] != '') {
|
||||||
static::$querySelect['select'] = ['1'];
|
static::$querySelect['select'] = ['1'];
|
||||||
static::$querySelect['orderBy'] = '';
|
static::$querySelect['orderBy'] = '';
|
||||||
|
|
||||||
$sql = 'SELECT COUNT(1) AS quantity FROM ('.static::buildQuery().') AS counted';
|
$sql = 'SELECT COUNT(1) AS quantity FROM (' . static::buildQuery() . ') AS counted';
|
||||||
$queryResult = static::query($sql, $resetQuery);
|
$queryResult = static::query($sql, $resetQuery);
|
||||||
$result = $queryResult[0]['quantity'];
|
$result = $queryResult[0]['quantity'];
|
||||||
} else {
|
} else {
|
||||||
static::$querySelect['select'] = ["COUNT(".static::table().".".static::$primaryKey.") as quantity"];
|
static::$querySelect['select'] = [
|
||||||
|
"COUNT(" . static::table() . "." . static::$primaryKey . ") as quantity",
|
||||||
|
];
|
||||||
static::$querySelect['limit'] = '1';
|
static::$querySelect['limit'] = '1';
|
||||||
static::$querySelect['orderBy'] = '';
|
static::$querySelect['orderBy'] = '';
|
||||||
|
|
||||||
@ -819,10 +851,10 @@ class Model {
|
|||||||
* Realiza una búsqueda en la tabla de la instancia actual.
|
* Realiza una búsqueda en la tabla de la instancia actual.
|
||||||
*
|
*
|
||||||
* @param string $search
|
* @param string $search
|
||||||
* Contenido a buscar.
|
* Contenido a buscar.
|
||||||
*
|
*
|
||||||
* @param array|null $in
|
* @param array|null $in
|
||||||
* (opcional) Columnas en las que se va a buscar (null para buscar en todas).
|
* (opcional) Columnas en las que se va a buscar (null para buscar en todas).
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
*/
|
*/
|
||||||
@ -836,18 +868,22 @@ class Model {
|
|||||||
$search = static::bindValue($search);
|
$search = static::bindValue($search);
|
||||||
$where = [];
|
$where = [];
|
||||||
|
|
||||||
if (DB_TYPE == 'sqlite')
|
if (DB_TYPE == 'sqlite') {
|
||||||
foreach($in as $row)
|
foreach ($in as $row) {
|
||||||
$where[] = "$row LIKE '%' || $search || '%'";
|
$where[] = "$row LIKE '%' || $search || '%'";
|
||||||
else
|
}
|
||||||
foreach($in as $row)
|
} else {
|
||||||
|
foreach ($in as $row) {
|
||||||
$where[] = "$row LIKE CONCAT('%', $search, '%')";
|
$where[] = "$row LIKE CONCAT('%', $search, '%')";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
if (static::$querySelect['where']=='')
|
if (static::$querySelect['where'] == '') {
|
||||||
static::$querySelect['where'] = join(' OR ', $where);
|
static::$querySelect['where'] = join(' OR ', $where);
|
||||||
else
|
} else {
|
||||||
static::$querySelect['where'] = static::$querySelect['where'] .' AND ('.join(' OR ', $where).')';
|
static::$querySelect['where'] = static::$querySelect['where'] . ' AND (' . join(' OR ', $where) . ')';
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
@ -856,10 +892,10 @@ class Model {
|
|||||||
* Obtener los resultados de la consulta SQL.
|
* Obtener los resultados de la consulta SQL.
|
||||||
*
|
*
|
||||||
* @param bool $resetQuery
|
* @param bool $resetQuery
|
||||||
* (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<static>
|
* @return array<static>
|
||||||
* Arreglo con instancias del la clase actual resultantes del query.
|
* Arreglo con instancias del la clase actual resultantes del query.
|
||||||
*/
|
*/
|
||||||
public static function get(bool $resetQuery = true): array
|
public static function get(bool $resetQuery = true): array
|
||||||
{
|
{
|
||||||
@ -879,10 +915,10 @@ class Model {
|
|||||||
* El primer elemento de la consulta SQL.
|
* El primer elemento de la consulta SQL.
|
||||||
*
|
*
|
||||||
* @param bool $resetQuery
|
* @param bool $resetQuery
|
||||||
* (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 static|null
|
* @return static|null
|
||||||
* Puede retornar una instancia de la clase actual o null.
|
* Puede retornar una instancia de la clase actual o null.
|
||||||
*/
|
*/
|
||||||
public static function getFirst(bool $resetQuery = true): ?static
|
public static function getFirst(bool $resetQuery = true): ?static
|
||||||
{
|
{
|
||||||
@ -895,17 +931,18 @@ class Model {
|
|||||||
* Obtener todos los elementos del la tabla de la instancia actual.
|
* Obtener todos los elementos del la tabla de la instancia actual.
|
||||||
*
|
*
|
||||||
* @return array<static>
|
* @return array<static>
|
||||||
* 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);
|
||||||
|
|
||||||
$instances = [];
|
$instances = [];
|
||||||
|
|
||||||
foreach ($result as $row)
|
foreach ($result as $row) {
|
||||||
$instances[] = static::getInstance($row);
|
$instances[] = static::getInstance($row);
|
||||||
|
}
|
||||||
|
|
||||||
return $instances;
|
return $instances;
|
||||||
}
|
}
|
||||||
@ -915,21 +952,23 @@ class Model {
|
|||||||
* 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 string|array $atts
|
||||||
* Atributo o arreglo de atributos que se definirán como nulos.
|
* Atributo o arreglo de atributos que se definirán como nulos.
|
||||||
*
|
*
|
||||||
* @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)) {
|
||||||
$this->toNull[] = $att;
|
$this->toNull[] = $att;
|
||||||
|
}
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!in_array($atts, $this->toNull))
|
if (!in_array($atts, $this->toNull)) {
|
||||||
$this->toNull[] = $atts;
|
$this->toNull[] = $atts;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
?>
|
|
||||||
|
@ -1,27 +1,27 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
|
use AllowDynamicProperties;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Neuron - DuckBrain
|
* Neuron - DuckBrain
|
||||||
*
|
*
|
||||||
* Neuron, sirve para crear un objeto que alojará valores, pero
|
* Neuron, sirve para crear un objeto que alojará valores.
|
||||||
* además tiene la característica especial de que al intentar
|
* Además, tiene la característica especial de que al intentar
|
||||||
* acceder a un atributo que no está definido devolerá nulo en
|
* acceder a una propiedad no definida, devolverá null en
|
||||||
* lugar de generar un error php notice que indica que se está
|
* lugar de generar un aviso (PHP notice) por variable o propiedad no definida.
|
||||||
* intentando acceder a un valor no definido.
|
|
||||||
*
|
*
|
||||||
* El constructor recibe un objeto o arreglo con los valores que
|
* El constructor acepta un objeto o un arreglo que contiene los
|
||||||
* sí estarán definidos.
|
* valores que estarán definidos.
|
||||||
*
|
*
|
||||||
* @author KJ
|
* @author KJ
|
||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace Libs;
|
|
||||||
use AllowDynamicProperties;
|
|
||||||
|
|
||||||
#[AllowDynamicProperties]
|
#[AllowDynamicProperties]
|
||||||
class Neuron {
|
class Neuron
|
||||||
|
{
|
||||||
/**
|
/**
|
||||||
* __construct
|
* __construct
|
||||||
*
|
*
|
||||||
@ -29,20 +29,24 @@ class Neuron {
|
|||||||
*/
|
*/
|
||||||
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]) ||
|
||||||
is_object($data[0])))
|
is_object($data[0]))
|
||||||
|
) {
|
||||||
$data = $data[0];
|
$data = $data[0];
|
||||||
|
}
|
||||||
|
|
||||||
foreach($data as $key => $value)
|
foreach ($data as $key => $value) {
|
||||||
$this->{$key} = $value;
|
$this->{$key} = $value;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* __get
|
* __get
|
||||||
*
|
*
|
||||||
* @param string $index
|
* @param string $index
|
||||||
* @return null
|
* @return null
|
||||||
*/
|
*/
|
||||||
public function __get(string $index): null
|
public function __get(string $index): null
|
||||||
@ -50,5 +54,3 @@ class Neuron {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
?>
|
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request - DuckBrain
|
* Request - DuckBrain
|
||||||
*
|
*
|
||||||
@ -9,10 +12,8 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class Request extends Neuron
|
||||||
namespace Libs;
|
{
|
||||||
|
|
||||||
class Request extends Neuron {
|
|
||||||
public Neuron $get;
|
public Neuron $get;
|
||||||
public Neuron $post;
|
public Neuron $post;
|
||||||
public Neuron $put;
|
public Neuron $put;
|
||||||
@ -23,12 +24,12 @@ class Request extends Neuron {
|
|||||||
public string $path;
|
public string $path;
|
||||||
public string $error;
|
public string $error;
|
||||||
public string $body;
|
public string $body;
|
||||||
public array $next;
|
public array $next;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* __construct
|
* __construct
|
||||||
*
|
*
|
||||||
* @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()
|
public function __construct()
|
||||||
{
|
{
|
||||||
@ -41,14 +42,19 @@ class Request extends Neuron {
|
|||||||
$this->body = file_get_contents("php://input");
|
$this->body = file_get_contents("php://input");
|
||||||
|
|
||||||
$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") {
|
||||||
$this->json = new Neuron(
|
$this->json = new Neuron(
|
||||||
(object) json_decode(trim($this->body), false)
|
(object) json_decode(trim($this->body), false)
|
||||||
);
|
);
|
||||||
else {
|
} else {
|
||||||
$this->json = new Neuron();
|
$this->json = new Neuron();
|
||||||
if (in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE']) &&
|
if (
|
||||||
preg_match('/^[^;?\/:@&=+$,]{1,255}[=]/', $this->body, $matches)) { // Con la expresión regular verificamos que sea un http query string válido y evitamos errores de memoria en caso de que el body tenga algo más grande que eso.
|
in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'PATCH', 'DELETE']) &&
|
||||||
|
preg_match('/^[^;?\/:@&=+$,]{1,255}[=]/', $this->body, $matches)
|
||||||
|
) {
|
||||||
|
// Con la expresión regular verificamos que sea un http
|
||||||
|
// query string válido y evitamos errores de memoria en caso
|
||||||
|
// de que el body tenga algo más grande que eso.
|
||||||
parse_str($this->body, $input_vars);
|
parse_str($this->body, $input_vars);
|
||||||
$this->{strtolower($_SERVER['REQUEST_METHOD'])} = new Neuron($input_vars);
|
$this->{strtolower($_SERVER['REQUEST_METHOD'])} = new Neuron($input_vars);
|
||||||
}
|
}
|
||||||
@ -64,8 +70,9 @@ class Request extends Neuron {
|
|||||||
*/
|
*/
|
||||||
public function handle(): mixed
|
public function handle(): mixed
|
||||||
{
|
{
|
||||||
if ($this->validate())
|
if ($this->validate()) {
|
||||||
return Middleware::next($this);
|
return Middleware::next($this);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -77,21 +84,23 @@ class Request extends Neuron {
|
|||||||
*/
|
*/
|
||||||
public function validate(): bool
|
public function validate(): bool
|
||||||
{
|
{
|
||||||
$actual = match($_SERVER['REQUEST_METHOD']) {
|
$actual = match ($_SERVER['REQUEST_METHOD']) {
|
||||||
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
|
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
|
||||||
default => $this->get
|
default => $this->get
|
||||||
};
|
};
|
||||||
|
|
||||||
if (Validator::validateList(static::paramRules(), $this->params) &&
|
if (
|
||||||
Validator::validateList(static::getRules(), $this->get ) &&
|
Validator::validateList(static::paramRules(), $this->params) &&
|
||||||
Validator::validateList(static::rules(), $actual))
|
Validator::validateList(static::getRules(), $this->get) &&
|
||||||
|
Validator::validateList(static::rules(), $actual)
|
||||||
|
) {
|
||||||
return true;
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
if (isset(static::messages()[Validator::$lastFailed]))
|
if (isset(static::messages()[Validator::$lastFailed])) {
|
||||||
$error = static::messages()[Validator::$lastFailed];
|
$error = static::messages()[Validator::$lastFailed];
|
||||||
else {
|
} else {
|
||||||
|
$error = 'Error: validation failed of ' . preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
|
||||||
$error = 'Error: validation failed of '.preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
static::onInvalid($error);
|
static::onInvalid($error);
|
||||||
@ -103,7 +112,8 @@ class Request extends Neuron {
|
|||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function rules(): array {
|
public function rules(): array
|
||||||
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -112,7 +122,8 @@ class Request extends Neuron {
|
|||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function paramRules(): array {
|
public function paramRules(): array
|
||||||
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -121,7 +132,8 @@ class Request extends Neuron {
|
|||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function getRules(): array {
|
public function getRules(): array
|
||||||
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -130,7 +142,8 @@ class Request extends Neuron {
|
|||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
*/
|
*/
|
||||||
public function messages(): array {
|
public function messages(): array
|
||||||
|
{
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Router - DuckBrain
|
* Router - DuckBrain
|
||||||
*
|
*
|
||||||
@ -10,17 +13,15 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class Router
|
||||||
namespace Libs;
|
{
|
||||||
|
|
||||||
class Router {
|
|
||||||
private static $get = [];
|
private static $get = [];
|
||||||
private static $post = [];
|
private static $post = [];
|
||||||
private static $put = [];
|
private static $put = [];
|
||||||
private static $patch = [];
|
private static $patch = [];
|
||||||
private static $delete = [];
|
private static $delete = [];
|
||||||
private static $last;
|
private static $last;
|
||||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Función callback por defectio para cuando
|
* Función callback por defectio para cuando
|
||||||
@ -28,7 +29,7 @@ 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>';
|
||||||
@ -37,21 +38,23 @@ class Router {
|
|||||||
/**
|
/**
|
||||||
* __construct
|
* __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
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
*
|
*
|
||||||
* @param callable $callback
|
* @param callable $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @return array
|
* @return array
|
||||||
* Arreglo con 2 índices:
|
* Arreglo con 2 índices:
|
||||||
* 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
|
||||||
{
|
{
|
||||||
@ -62,12 +65,13 @@ class Router {
|
|||||||
$path = preg_replace(
|
$path = preg_replace(
|
||||||
['/\\\{\w+\\\}/s'],
|
['/\\\{\w+\\\}/s'],
|
||||||
['([^\/]+)'],
|
['([^\/]+)'],
|
||||||
$path);
|
$path
|
||||||
|
);
|
||||||
|
|
||||||
return [
|
return [
|
||||||
'path' => $path,
|
'path' => $path,
|
||||||
'callback' => [$callback],
|
'callback' => [$callback],
|
||||||
'paramNames' => $paramNames
|
'paramNames' => $paramNames,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -82,8 +86,9 @@ class Router {
|
|||||||
*/
|
*/
|
||||||
public static function basePath(): string
|
public static function basePath(): string
|
||||||
{
|
{
|
||||||
if (defined('SITE_URL') && !empty(SITE_URL))
|
if (defined('SITE_URL') && !empty(SITE_URL)) {
|
||||||
return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/').'/';
|
return rtrim(parse_url(SITE_URL, PHP_URL_PATH), '/') . '/';
|
||||||
|
}
|
||||||
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
|
return str_replace($_SERVER['DOCUMENT_ROOT'], '/', ROOT_DIR);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -91,7 +96,7 @@ class Router {
|
|||||||
* Redirije a una ruta relativa interna.
|
* Redirije a una ruta relativa interna.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* La ruta relativa a la ruta base.
|
* La ruta relativa a la ruta base.
|
||||||
*
|
*
|
||||||
* 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
|
||||||
@ -100,7 +105,7 @@ class Router {
|
|||||||
*/
|
*/
|
||||||
public static function redirect(string $path): void
|
public static function redirect(string $path): void
|
||||||
{
|
{
|
||||||
header('Location: '.static::basePath().ltrim($path, '/'));
|
header('Location: ' . static::basePath() . ltrim($path, '/'));
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,25 +114,27 @@ class Router {
|
|||||||
* Solo se puede usar un middleware a la vez.
|
* Solo se puede usar un middleware a la vez.
|
||||||
*
|
*
|
||||||
* @param callable $callback
|
* @param callable $callback
|
||||||
* @param int $prioriry
|
* @param int $prioriry
|
||||||
*
|
*
|
||||||
* @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();
|
||||||
|
}
|
||||||
|
|
||||||
$method = static::$last[0];
|
$method = static::$last[0];
|
||||||
$index = static::$last[1];
|
$index = static::$last[1];
|
||||||
|
|
||||||
if (isset($priority) && $priority <= 0)
|
if (isset($priority) && $priority <= 0) {
|
||||||
$priority = 1;
|
$priority = 1;
|
||||||
|
}
|
||||||
|
|
||||||
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback']))
|
if (is_null($priority) || $priority >= count(static::$$method[$index]['callback'])) {
|
||||||
static::$$method[$index]['callback'][] = $callback;
|
static::$$method[$index]['callback'][] = $callback;
|
||||||
else {
|
} else {
|
||||||
static::$$method[$index]['callback'] = array_merge(
|
static::$$method[$index]['callback'] = array_merge(
|
||||||
array_slice(static::$$method[$index]['callback'], 0, $priority),
|
array_slice(static::$$method[$index]['callback'], 0, $priority),
|
||||||
[$callback],
|
[$callback],
|
||||||
@ -147,8 +154,9 @@ class Router {
|
|||||||
*/
|
*/
|
||||||
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();
|
||||||
|
}
|
||||||
|
|
||||||
$method = static::$last[0];
|
$method = static::$last[0];
|
||||||
$index = static::$last[1];
|
$index = static::$last[1];
|
||||||
@ -165,10 +173,10 @@ class Router {
|
|||||||
* solo configura la ruta como la última configurada
|
* solo configura la ruta como la última configurada
|
||||||
* siempre y cuando la misma haya sido configurada previamente.
|
* siempre y cuando la misma haya sido configurada previamente.
|
||||||
*
|
*
|
||||||
* @param string $method
|
* @param string $method
|
||||||
* Método http.
|
* Método http.
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
*
|
*
|
||||||
* @return
|
* @return
|
||||||
@ -181,32 +189,34 @@ class Router {
|
|||||||
$path = preg_replace(
|
$path = preg_replace(
|
||||||
['/\\\{\w+\\\}/s'],
|
['/\\\{\w+\\\}/s'],
|
||||||
['([^\/]+)'],
|
['([^\/]+)'],
|
||||||
$path);
|
$path
|
||||||
|
);
|
||||||
|
|
||||||
foreach(static::$$method as $index => $router)
|
foreach (static::$$method as $index => $router) {
|
||||||
if ($router['path'] == $path) {
|
if ($router['path'] == $path) {
|
||||||
static::$last = [$method, $index];
|
static::$last = [$method, $index];
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
|
|
||||||
static::$$method[] = static::parse($path, $callback);
|
static::$$method[] = static::parse($path, $callback);
|
||||||
static::$last = [$method, count(static::$$method)-1];
|
static::$last = [$method, count(static::$$method) - 1];
|
||||||
return new static();
|
return new static();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Define los routers para el método GET.
|
* Define los routers para el método GET.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -216,13 +226,13 @@ class Router {
|
|||||||
/**
|
/**
|
||||||
* Define los routers para el método POST.
|
* Define los routers para el método POST.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -232,13 +242,13 @@ class Router {
|
|||||||
/**
|
/**
|
||||||
* Define los routers para el método PUT.
|
* Define los routers para el método PUT.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @return static
|
* @return static
|
||||||
* 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
|
||||||
@ -249,13 +259,13 @@ class Router {
|
|||||||
/**
|
/**
|
||||||
* Define los routers para el método PATCH.
|
* Define los routers para el método PATCH.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables.
|
* Ruta con pseudovariables.
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -265,13 +275,13 @@ class Router {
|
|||||||
/**
|
/**
|
||||||
* Define los routers para el método DELETE.
|
* Define los routers para el método DELETE.
|
||||||
*
|
*
|
||||||
* @param string $path
|
* @param string $path
|
||||||
* Ruta con pseudovariables
|
* Ruta con pseudovariables
|
||||||
* @param callable|null $callback
|
* @param callable|null $callback
|
||||||
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
* Callback que será llamado cuando la ruta configurada en $path coincida.
|
||||||
*
|
*
|
||||||
* @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
|
||||||
{
|
{
|
||||||
@ -283,10 +293,14 @@ 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(
|
||||||
'/', strtok($_SERVER['REQUEST_URI'], '?'), 1);
|
'/' . preg_quote(static::basePath(), '/') . '/',
|
||||||
|
'/',
|
||||||
|
strtok($_SERVER['REQUEST_URI'], '?'),
|
||||||
|
1
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -299,7 +313,7 @@ class Router {
|
|||||||
public static function apply(?string $path = null): void
|
public static function apply(?string $path = null): void
|
||||||
{
|
{
|
||||||
$path = $path ?? static::currentPath();
|
$path = $path ?? static::currentPath();
|
||||||
$routers = match($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
|
$routers = match ($_SERVER['REQUEST_METHOD']) { // Según el método selecciona un arreglo de routers
|
||||||
'POST' => static::$post,
|
'POST' => static::$post,
|
||||||
'PUT' => static::$put,
|
'PUT' => static::$put,
|
||||||
'PATCH' => static::$patch,
|
'PATCH' => static::$patch,
|
||||||
@ -308,7 +322,7 @@ class Router {
|
|||||||
};
|
};
|
||||||
|
|
||||||
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual
|
foreach ($routers as $router) { // revisa todos los routers para ver si coinciden con la ruta actual
|
||||||
if (preg_match_all('/^'.$router['path'].'\/?$/si',$path, $matches, PREG_PATTERN_ORDER)) {
|
if (preg_match_all('/^' . $router['path'] . '\/?$/si', $path, $matches, PREG_PATTERN_ORDER)) {
|
||||||
unset($matches[0]);
|
unset($matches[0]);
|
||||||
|
|
||||||
// Objtener un reflection del callback
|
// Objtener un reflection del callback
|
||||||
@ -316,14 +330,16 @@ class Router {
|
|||||||
if ($lastCallback instanceof \Closure) { // si es función anónima
|
if ($lastCallback instanceof \Closure) { // si es función anónima
|
||||||
$reflectionCallback = new \ReflectionFunction($lastCallback);
|
$reflectionCallback = new \ReflectionFunction($lastCallback);
|
||||||
} else {
|
} else {
|
||||||
if (is_string($lastCallback))
|
if (is_string($lastCallback)) {
|
||||||
$lastCallback = preg_split('/::/', $lastCallback);
|
$lastCallback = preg_split('/::/', $lastCallback);
|
||||||
|
}
|
||||||
|
|
||||||
// Revisamos su es un método o solo una función
|
// Revisamos su es un método o solo una función
|
||||||
if (count($lastCallback) == 2)
|
if (count($lastCallback) == 2) {
|
||||||
$reflectionCallback = new \ReflectionMethod($lastCallback[0], $lastCallback[1]);
|
$reflectionCallback = new \ReflectionMethod($lastCallback[0], $lastCallback[1]);
|
||||||
else
|
} else {
|
||||||
$reflectionCallback = new \ReflectionFunction($lastCallback[0]);
|
$reflectionCallback = new \ReflectionFunction($lastCallback[0]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtener los parámetros
|
// Obtener los parámetros
|
||||||
@ -334,22 +350,23 @@ class Router {
|
|||||||
|
|
||||||
// Verificamos si la clase está o no tipada
|
// Verificamos si la clase está o no tipada
|
||||||
if (empty($argumentClass)) {
|
if (empty($argumentClass)) {
|
||||||
$request = new Request;
|
$request = new Request();
|
||||||
} else {
|
} else {
|
||||||
$request = new $argumentClass;
|
$request = new $argumentClass();
|
||||||
|
|
||||||
// Verificamos que sea instancia de Request (requerimiento)
|
// Verificamos que sea instancia de Request (requerimiento)
|
||||||
if (!($request instanceof Request))
|
if (!($request instanceof Request)) {
|
||||||
throw new \Exception('Bad argument type on router callback.');
|
throw new \Exception('Bad argument type on router callback.');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
$request = new Request;
|
$request = new Request();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Comprobando y guardando los parámetros variables de la ruta
|
// Comprobando y guardando los parámetros variables de la ruta
|
||||||
if (isset($matches[1])) {
|
if (isset($matches[1])) {
|
||||||
foreach ($matches as $index => $match) {
|
foreach ($matches as $index => $match) {
|
||||||
$paramName = $router['paramNames'][$index-1];
|
$paramName = $router['paramNames'][$index - 1];
|
||||||
$request->params->$paramName = urldecode($match[0]);
|
$request->params->$paramName = urldecode($match[0]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -369,6 +386,6 @@ class Router {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Si no hay router que coincida llamamos a $notFoundCallBack
|
// Si no hay router que coincida llamamos a $notFoundCallBack
|
||||||
call_user_func_array(static::$notFoundCallback, [new Request]);
|
call_user_func_array(static::$notFoundCallback, [new Request()]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validator - DuckBrain
|
* Validator - DuckBrain
|
||||||
*
|
*
|
||||||
@ -28,10 +31,8 @@
|
|||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class Validator
|
||||||
namespace Libs;
|
{
|
||||||
|
|
||||||
class Validator {
|
|
||||||
public static string $lastFailed = '';
|
public static string $lastFailed = '';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -40,16 +41,17 @@ class Validator {
|
|||||||
* @param array $rulesList Lista de reglas.
|
* @param array $rulesList Lista de reglas.
|
||||||
* @param Neuron $haystack Objeto al que se le verificarán las reglas.
|
* @param Neuron $haystack Objeto al que se le verificarán las reglas.
|
||||||
*
|
*
|
||||||
* @return bool Retorna true solo si todas las reglas se cumplen y false en cuanto una falle.
|
* @return bool Retorna true solo si todas las reglas se cumplen y false en cuanto una falle.
|
||||||
*/
|
*/
|
||||||
public static function validateList(array $rulesList, Neuron $haystack): bool
|
public static function validateList(array $rulesList, Neuron $haystack): bool
|
||||||
{
|
{
|
||||||
foreach ($rulesList as $target => $rules) {
|
foreach ($rulesList as $target => $rules) {
|
||||||
$rules = preg_split('/\|/', $rules);
|
$rules = preg_split('/\|/', $rules);
|
||||||
foreach ($rules as $rule) {
|
foreach ($rules as $rule) {
|
||||||
if (static::checkRule($haystack->{$target}, $rule))
|
if (static::checkRule($haystack->{$target}, $rule)) {
|
||||||
continue;
|
continue;
|
||||||
static::$lastFailed = $target.'.'.$rule;
|
}
|
||||||
|
static::$lastFailed = $target . '.' . $rule;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -71,10 +73,11 @@ class Validator {
|
|||||||
$rule = [static::class, $arguments[0]];
|
$rule = [static::class, $arguments[0]];
|
||||||
$arguments[0] = $subject;
|
$arguments[0] = $subject;
|
||||||
|
|
||||||
if (is_callable($rule))
|
if (is_callable($rule)) {
|
||||||
return call_user_func_array($rule, $arguments);
|
return call_user_func_array($rule, $arguments);
|
||||||
|
}
|
||||||
|
|
||||||
throw new \Exception('Bad rule: "'.preg_split('/::/', $rule)[1].'"' );
|
throw new \Exception('Bad rule: "' . preg_split('/::/', $rule)[1] . '"');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -1,4 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
namespace Libs;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* View - DuckBrain
|
* View - DuckBrain
|
||||||
*
|
*
|
||||||
@ -7,12 +10,9 @@
|
|||||||
* @author KJ
|
* @author KJ
|
||||||
* @website https://kj2.me
|
* @website https://kj2.me
|
||||||
* @licence MIT
|
* @licence MIT
|
||||||
*/
|
*/
|
||||||
|
class View extends Neuron
|
||||||
namespace Libs;
|
{
|
||||||
|
|
||||||
class View extends Neuron {
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Incluye el archivo.
|
* Incluye el archivo.
|
||||||
*
|
*
|
||||||
@ -23,39 +23,39 @@ class View extends Neuron {
|
|||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
protected function include(
|
protected function include(
|
||||||
string $viewName,
|
string $viewName,
|
||||||
?string $viewPath = null,
|
?string $viewPath = null,
|
||||||
string $extension = 'php'
|
string $extension = 'php'
|
||||||
): void
|
): void {
|
||||||
{
|
if (
|
||||||
$view = $this;
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
include(ROOT_CORE."/Views/$viewName.$extension");
|
include(ROOT_CORE . "/Views/$viewName.$extension");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Función que "renderiza" las vistas
|
* Función que "renderiza" las vistas
|
||||||
*
|
*
|
||||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo.
|
||||||
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista mediante $view ($param['index'] se usaría así: $view->index)
|
* @param array|Neuron $params (opcional) Arreglo que podrá ser usado en la vista
|
||||||
* @param string|null $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/".
|
* mediante $view ($param['index'] se usaría así: $view->index)
|
||||||
* @param string $extension (opcional) Extensión del archivo.
|
* @param string|null $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/".
|
||||||
|
* @param string $extension (opcional) Extensión del archivo.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public static function render(
|
public static function render(
|
||||||
string $viewName,
|
string $viewName,
|
||||||
array|Neuron $params = [],
|
array|Neuron $params = [],
|
||||||
?string $viewPath = null,
|
?string $viewPath = null,
|
||||||
string $extension = 'php'
|
string $extension = 'php'
|
||||||
): void
|
): void {
|
||||||
{
|
|
||||||
$instance = new View($params);
|
$instance = new View($params);
|
||||||
$instance->html($viewName, $viewPath, $extension);
|
$instance->html($viewName, $viewPath, $extension);
|
||||||
}
|
}
|
||||||
@ -64,17 +64,17 @@ class View extends Neuron {
|
|||||||
* Renderiza las vistas HTML
|
* Renderiza las vistas HTML
|
||||||
*
|
*
|
||||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||||
* @param string|null $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/".
|
* @param string|null $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/".
|
||||||
* @param string $extension (opcional) Extensión del archivo.
|
* @param string $extension (opcional) Extensión del archivo.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function html(
|
public function html(
|
||||||
string $viewName,
|
string $viewName,
|
||||||
?string $viewPath = null,
|
?string $viewPath = null,
|
||||||
string $extension = 'php'
|
string $extension = 'php'
|
||||||
): void
|
): void {
|
||||||
{
|
|
||||||
$this->include(
|
$this->include(
|
||||||
$viewName,
|
$viewName,
|
||||||
$viewPath,
|
$viewPath,
|
||||||
@ -86,17 +86,17 @@ class View extends Neuron {
|
|||||||
* Renderiza código CSS.
|
* Renderiza código CSS.
|
||||||
*
|
*
|
||||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||||
* @param string|null $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/".
|
* @param string|null $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/".
|
||||||
* @param string $extension (opcional) Extensión del archivo.
|
* @param string $extension (opcional) Extensión del archivo.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function css(
|
public function css(
|
||||||
string $viewName,
|
string $viewName,
|
||||||
?string $viewPath = null,
|
?string $viewPath = null,
|
||||||
string $extension = 'css'
|
string $extension = 'css'
|
||||||
): void
|
): void {
|
||||||
{
|
|
||||||
header("Content-type: text/css");
|
header("Content-type: text/css");
|
||||||
$this->include($viewName, $viewPath, $extension);
|
$this->include($viewName, $viewPath, $extension);
|
||||||
}
|
}
|
||||||
@ -105,17 +105,17 @@ class View extends Neuron {
|
|||||||
* Renderiza código Javascript.
|
* Renderiza código Javascript.
|
||||||
*
|
*
|
||||||
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
* @param string $viewName Ruta relativa y el nommbre sin extensión del archivo ubicado en src/Views
|
||||||
* @param string|null $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/".
|
* @param string|null $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/".
|
||||||
* @param string $extension (opcional) Extensión del archivo.
|
* @param string $extension (opcional) Extensión del archivo.
|
||||||
*
|
*
|
||||||
* @return void
|
* @return void
|
||||||
*/
|
*/
|
||||||
public function js(
|
public function js(
|
||||||
string $viewName,
|
string $viewName,
|
||||||
?string $viewPath = null,
|
?string $viewPath = null,
|
||||||
string $extension = 'js'
|
string $extension = 'js'
|
||||||
): void
|
): void {
|
||||||
{
|
|
||||||
header("Content-type: application/javascript");
|
header("Content-type: application/javascript");
|
||||||
$this->include($viewName, $viewPath, $extension);
|
$this->include($viewName, $viewPath, $extension);
|
||||||
}
|
}
|
||||||
@ -155,10 +155,10 @@ class View extends Neuron {
|
|||||||
*/
|
*/
|
||||||
public static function route(string $path = '/'): string
|
public static function route(string $path = '/'): string
|
||||||
{
|
{
|
||||||
if (defined('SITE_URL') && !empty(SITE_URL))
|
if (defined('SITE_URL') && !empty(SITE_URL)) {
|
||||||
return rtrim(SITE_URL, '/').'/'.ltrim($path, '/');
|
return rtrim(SITE_URL, '/') . '/' . ltrim($path, '/');
|
||||||
|
}
|
||||||
|
|
||||||
return $path;
|
return $path;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
?>
|
|
||||||
|
Reference in New Issue
Block a user