Compare commits
33
Commits
c5a4967ae4
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b6da45b01 | ||
|
|
b7260b5199 | ||
|
|
1f29622914 | ||
|
|
eb882db0c8 | ||
|
|
9ba43e3f25 | ||
|
|
54e96ba4bb | ||
|
|
9027f36748 | ||
|
|
2ae9ef39f3 | ||
|
|
ee0db0307e | ||
|
|
44cbe6bbdc | ||
|
|
31728af351 | ||
|
|
4845d14ef5 | ||
|
|
aca4e732ed | ||
|
|
f475c9125f | ||
|
|
4fe7314389 | ||
|
|
1f366830bc | ||
|
|
15df7c8d96 | ||
|
|
b8dd1fd0f6 | ||
|
|
83c80bd4ab | ||
|
|
b13c07d3c4 | ||
|
|
b95747bfe0 | ||
|
|
01c5eceeb4 | ||
|
|
ee9c109ed9 | ||
|
|
7eed69725d | ||
|
|
e37035eed8 | ||
|
|
5312e5060e | ||
|
|
3c9db3ac53 | ||
|
|
2b5d19ecd5 | ||
|
|
53e862d126 | ||
|
|
b6baeef32f | ||
|
|
159da01d5c | ||
|
|
3770dd6d9b | ||
|
|
76a69e5ef8 |
+220
-157
@@ -23,40 +23,40 @@ use ReflectionProperty;
|
||||
#[AllowDynamicProperties]
|
||||
class Model
|
||||
{
|
||||
/**
|
||||
* @var array Attributes that should be set to NULL on update.
|
||||
*/
|
||||
protected array $toNull = [];
|
||||
|
||||
/**
|
||||
* @var string The name of the primary key column.
|
||||
*/
|
||||
protected static string $primaryKey = 'id';
|
||||
protected static string $dbPrimaryKey = 'id';
|
||||
|
||||
/**
|
||||
* @var array Attributes to ignore when saving to the database.
|
||||
*/
|
||||
protected static array $ignoreSave = ['id'];
|
||||
protected static array $dbIgnoreSave = [];
|
||||
|
||||
/**
|
||||
* @var array Attributes that should be explicitly saved, even if private/protected.
|
||||
*/
|
||||
protected static array $forceSave = [];
|
||||
protected static array $dbForceSave = [];
|
||||
|
||||
/**
|
||||
* @var bool Attribute that persis if is current model is saved into the database
|
||||
*/
|
||||
protected bool $dbIsSaved = false;
|
||||
|
||||
/**
|
||||
* @var string The database table name.
|
||||
*/
|
||||
protected static string $table;
|
||||
protected static string $dbTableName;
|
||||
|
||||
/**
|
||||
* @var array Variables for PDO prepared statements.
|
||||
*/
|
||||
protected static array $queryVars = [];
|
||||
protected static array $dbQueryVariables = [];
|
||||
|
||||
/**
|
||||
* @var array Current SELECT query components.
|
||||
*/
|
||||
protected static array $querySelect = [
|
||||
protected static array $dbQuery = [
|
||||
'select' => ['*'],
|
||||
'where' => '',
|
||||
'from' => '',
|
||||
@@ -156,13 +156,29 @@ class Model
|
||||
|
||||
try {
|
||||
$prepared = $db->prepare($query);
|
||||
$prepared->execute(static::$queryVars);
|
||||
foreach (static::$dbQueryVariables as $key => $value) {
|
||||
// Detect data type to choose the PDO constant
|
||||
$type = match (gettype($value)) {
|
||||
'integer' => PDO::PARAM_INT,
|
||||
'boolean' => PDO::PARAM_BOOL,
|
||||
'NULL' => PDO::PARAM_NULL,
|
||||
default => PDO::PARAM_STR,
|
||||
};
|
||||
|
||||
$prepared->bindValue($key, $value, $type);
|
||||
}
|
||||
|
||||
$prepared->execute();
|
||||
} catch (PDOException $e) {
|
||||
if ($db->inTransaction()) {
|
||||
$db->rollBack();
|
||||
}
|
||||
|
||||
$vars = json_encode(static::$queryVars);
|
||||
$vars = json_encode(static::$dbQueryVariables);
|
||||
|
||||
if ($resetQuery) {
|
||||
static::resetQuery();
|
||||
}
|
||||
|
||||
throw new Exception(
|
||||
"\nError at query to database.\n" .
|
||||
@@ -187,7 +203,7 @@ class Model
|
||||
*/
|
||||
protected static function resetQuery(): void
|
||||
{
|
||||
static::$querySelect = [
|
||||
static::$dbQuery = [
|
||||
'select' => ['*'],
|
||||
'where' => '',
|
||||
'from' => '',
|
||||
@@ -199,7 +215,7 @@ class Model
|
||||
'groupBy' => '',
|
||||
'limit' => '',
|
||||
];
|
||||
static::$queryVars = [];
|
||||
static::$dbQueryVariables = [];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,44 +227,44 @@ class Model
|
||||
*/
|
||||
protected static function buildQuery(): string
|
||||
{
|
||||
$sql = 'SELECT ' . join(', ', static::$querySelect['select']);
|
||||
$sql = 'SELECT ' . join(', ', static::$dbQuery['select']);
|
||||
|
||||
if (static::$querySelect['from'] != '') {
|
||||
$sql .= ' FROM ' . static::$querySelect['from'];
|
||||
if (static::$dbQuery['from'] != '') {
|
||||
$sql .= ' FROM ' . static::$dbQuery['from'];
|
||||
} else {
|
||||
$sql .= ' FROM ' . static::table();
|
||||
}
|
||||
|
||||
if (static::$querySelect['crossJoin'] != '') {
|
||||
$sql .= static::$querySelect['crossJoin'];
|
||||
if (static::$dbQuery['crossJoin'] != '') {
|
||||
$sql .= static::$dbQuery['crossJoin'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['innerJoin'] != '') {
|
||||
$sql .= static::$querySelect['innerJoin'];
|
||||
if (static::$dbQuery['innerJoin'] != '') {
|
||||
$sql .= static::$dbQuery['innerJoin'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['leftJoin'] != '') {
|
||||
$sql .= static::$querySelect['leftJoin'];
|
||||
if (static::$dbQuery['leftJoin'] != '') {
|
||||
$sql .= static::$dbQuery['leftJoin'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['rightJoin'] != '') {
|
||||
$sql .= static::$querySelect['rightJoin'];
|
||||
if (static::$dbQuery['rightJoin'] != '') {
|
||||
$sql .= static::$dbQuery['rightJoin'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['where'] != '') {
|
||||
$sql .= ' WHERE ' . static::$querySelect['where'];
|
||||
if (static::$dbQuery['where'] != '') {
|
||||
$sql .= ' WHERE ' . static::$dbQuery['where'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['groupBy'] != '') {
|
||||
$sql .= ' GROUP BY ' . static::$querySelect['groupBy'];
|
||||
if (static::$dbQuery['groupBy'] != '') {
|
||||
$sql .= ' GROUP BY ' . static::$dbQuery['groupBy'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['orderBy'] != '') {
|
||||
$sql .= ' ORDER BY ' . static::$querySelect['orderBy'];
|
||||
if (static::$dbQuery['orderBy'] != '') {
|
||||
$sql .= ' ORDER BY ' . static::$dbQuery['orderBy'];
|
||||
}
|
||||
|
||||
if (static::$querySelect['limit'] != '') {
|
||||
$sql .= ' LIMIT ' . static::$querySelect['limit'];
|
||||
if (static::$dbQuery['limit'] != '') {
|
||||
$sql .= ' LIMIT ' . static::$dbQuery['limit'];
|
||||
}
|
||||
|
||||
return $sql;
|
||||
@@ -267,8 +283,8 @@ class Model
|
||||
*/
|
||||
public static function bind(string $value): string
|
||||
{
|
||||
$index = ':v_' . count(static::$queryVars);
|
||||
static::$queryVars[$index] = $value;
|
||||
$index = ':v_' . count(static::$dbQueryVariables);
|
||||
static::$dbQueryVariables[$index] = $value;
|
||||
return $index;
|
||||
}
|
||||
|
||||
@@ -284,30 +300,65 @@ class Model
|
||||
*/
|
||||
protected static function getInstance(array $elem = []): static
|
||||
{
|
||||
$class = get_called_class();
|
||||
$instance = new $class();
|
||||
$reflection = new ReflectionClass($instance);
|
||||
$properties = $reflection->getProperties();
|
||||
$propertyNames = array_map(function ($property) {
|
||||
return static::camelCaseToSnakeCase($property->name);
|
||||
}, $properties);
|
||||
$class = get_called_class();
|
||||
$instance = new $class();
|
||||
$reflection = new ReflectionClass($instance);
|
||||
$properties = $reflection->getProperties();
|
||||
|
||||
$map = [];
|
||||
foreach ($properties as $prop) {
|
||||
$map[static::camelCaseToSnakeCase($prop->name)] = $prop;
|
||||
}
|
||||
|
||||
foreach ($elem as $key => $value) {
|
||||
$index = array_search($key, $propertyNames);
|
||||
if (is_numeric($index)) {
|
||||
if (enum_exists($properties[$index]->getType()->getName())) {
|
||||
$instance->{$properties[$index]->name} = $properties[$index]->getType()->getName()::tryfrom($value);
|
||||
} else {
|
||||
$instance->{$properties[$index]->name} = $value;
|
||||
}
|
||||
if (isset($map[$key])) {
|
||||
$property = $map[$key];
|
||||
$instance->{$property->name} = static::castValue($property, $value);
|
||||
} else {
|
||||
$instance->{static::snakeCaseToCamelCase($key)} = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$instance->markAsSaved();
|
||||
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles type casting for properties
|
||||
*
|
||||
* @param ReflectionProperty $property
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
protected static function castValue(ReflectionProperty $property, mixed $value): mixed
|
||||
{
|
||||
$type = $property->getType();
|
||||
if (!$type) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$typeName = $type->getName();
|
||||
|
||||
// Enum cast
|
||||
if (enum_exists($typeName)) {
|
||||
if (method_exists($typeName, 'tryFrom')) {
|
||||
return $typeName::tryFrom($value);
|
||||
}
|
||||
if (in_array($value, array_column($typeName::cases(), 'name'))) {
|
||||
return $typeName::{$value};
|
||||
}
|
||||
}
|
||||
|
||||
// DateTime cast
|
||||
if (is_subclass_of($typeName, \DateTimeInterface::class)) {
|
||||
return $value ? new $typeName($value) : null;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the attributes to be saved for the current class.
|
||||
* Attributes will be those that are public and not excluded in static::$ignoreSave,
|
||||
@@ -323,30 +374,43 @@ class Model
|
||||
$result = [];
|
||||
|
||||
foreach ($properties as $property) {
|
||||
if (!in_array($property->name, static::$ignoreSave)) {
|
||||
$result[$this->camelCaseToSnakeCase($property->name)] = isset($this->{$property->name})
|
||||
? $this->{$property->name} : null;
|
||||
// Avoid save unset variables
|
||||
if ($property->getType() && !$property->isInitialized($this)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!in_array($property->name, static::$dbIgnoreSave)) {
|
||||
$name = $this->camelCaseToSnakeCase($property->name);
|
||||
$result[$name] = $this->castToDbValue($this->{$property->name});
|
||||
}
|
||||
}
|
||||
|
||||
foreach (static::$forceSave as $value) {
|
||||
$result[$value] = isset($this->$value)
|
||||
? $this->$value : null;
|
||||
}
|
||||
|
||||
foreach ($result as $i => $property) {
|
||||
if (gettype($property) == 'boolean') {
|
||||
$result[$i] = $property ? '1' : '0';
|
||||
}
|
||||
|
||||
if ($property instanceof \UnitEnum) {
|
||||
$result[$i] = $property->value ?? $property->name;
|
||||
}
|
||||
foreach (static::$dbForceSave as $value) {
|
||||
$result[$value] = $this->castToDbValue($this->$value);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a PHP value to a database-compatible value.
|
||||
*
|
||||
* @param mixed $value
|
||||
* @return mixed
|
||||
*/
|
||||
protected function castToDbValue(mixed $value): mixed
|
||||
{
|
||||
if ($value instanceof \UnitEnum) {
|
||||
return $value->value ?? $value->name;
|
||||
}
|
||||
|
||||
if ($value instanceof \DateTimeInterface) {
|
||||
return $value->format('Y-m-d H:i:s');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the current class, even if it's an extended class.
|
||||
*
|
||||
@@ -370,8 +434,8 @@ class Model
|
||||
*/
|
||||
protected static function table(): string
|
||||
{
|
||||
if (isset(static::$table)) {
|
||||
return static::$table;
|
||||
if (isset(static::$dbTableName)) {
|
||||
return static::$dbTableName;
|
||||
}
|
||||
|
||||
return static::camelCaseToSnakeCase(static::className()) . 's';
|
||||
@@ -416,26 +480,20 @@ class Model
|
||||
protected function update(): void
|
||||
{
|
||||
$atts = $this->getVars();
|
||||
static::$dbQueryVariables = [];
|
||||
|
||||
$set = [];
|
||||
foreach ($atts as $key => $value) {
|
||||
if (isset($value)) {
|
||||
if (in_array($key, $this->toNull)) {
|
||||
$set[] = "$key=NULL";
|
||||
} else {
|
||||
$set[] = "$key=:$key";
|
||||
static::$queryVars[':' . $key] = $value;
|
||||
}
|
||||
} else {
|
||||
if (in_array($key, $this->toNull)) {
|
||||
$set[] = "$key=NULL";
|
||||
}
|
||||
}
|
||||
$set[] = "$key=:$key";
|
||||
static::$dbQueryVariables[':' . $key] = $value;
|
||||
}
|
||||
|
||||
$table = static::table();
|
||||
$pk = static::$primaryKey;
|
||||
$pk = static::$dbPrimaryKey;
|
||||
$pkv = $this->$pk;
|
||||
$sql = "UPDATE $table SET " . join(', ', $set) . " WHERE $pk='$pkv'";
|
||||
$sql = "UPDATE $table SET " . join(', ', $set) . " WHERE $pk=:$pk";
|
||||
static::$dbQueryVariables[":$pk"] = $pkv;
|
||||
|
||||
static::query($sql);
|
||||
}
|
||||
|
||||
@@ -450,38 +508,48 @@ class Model
|
||||
$atts = $this->getVars();
|
||||
$into = [];
|
||||
$values = [];
|
||||
static::$dbQueryVariables = [];
|
||||
|
||||
foreach ($atts as $key => $value) {
|
||||
if (isset($value)) {
|
||||
$into[] = "$key";
|
||||
$values[] = ":$key";
|
||||
static::$queryVars[":$key"] = $value;
|
||||
}
|
||||
$into[] = "$key";
|
||||
$values[] = ":$key";
|
||||
static::$dbQueryVariables[":$key"] = $value;
|
||||
}
|
||||
|
||||
$table = static::table();
|
||||
$sql = "INSERT INTO $table (" . join(', ', $into) . ") VALUES (" . join(', ', $values) . ")";
|
||||
static::query($sql);
|
||||
|
||||
$pk = static::$primaryKey;
|
||||
$this->$pk = $db->lastInsertId();
|
||||
$pk = static::$dbPrimaryKey;
|
||||
$this->$pk ??= $db->lastInsertId();
|
||||
$this->markAsSaved();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the object to be saved is new or not, and based on the result,
|
||||
* calls `update` to update an existing row or `add` to insert a new row.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function save(): void
|
||||
{
|
||||
$pk = static::$primaryKey;
|
||||
if (isset($this->$pk)) {
|
||||
if ($this->dbIsSaved) {
|
||||
$this->update();
|
||||
} else {
|
||||
$this->add();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark the current instance as already saved
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function markAsSaved(): void
|
||||
{
|
||||
$this->dbIsSaved = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the current object from the database.
|
||||
* @return void
|
||||
@@ -489,11 +557,12 @@ class Model
|
||||
public function delete(): void
|
||||
{
|
||||
$table = static::table();
|
||||
$pk = static::$primaryKey;
|
||||
$pk = static::$dbPrimaryKey;
|
||||
$sql = "DELETE FROM $table WHERE $pk=:$pk";
|
||||
|
||||
static::$queryVars[":$pk"] = $this->$pk;
|
||||
static::$dbQueryVariables[":$pk"] = $this->$pk;
|
||||
static::query($sql);
|
||||
$this->dbIsSaved = false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -506,7 +575,7 @@ class Model
|
||||
*/
|
||||
public static function select(string ...$columns): static
|
||||
{
|
||||
static::$querySelect['select'] = $columns;
|
||||
static::$dbQuery['select'] = $columns;
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -521,7 +590,7 @@ class Model
|
||||
*/
|
||||
public static function from(...$tables): static
|
||||
{
|
||||
static::$querySelect['from'] = join(', ', $tables);
|
||||
static::$dbQuery['from'] = join(', ', $tables);
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -591,10 +660,10 @@ class Model
|
||||
$value = static::bind($value);
|
||||
}
|
||||
|
||||
if (static::$querySelect['where'] == '') {
|
||||
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
||||
if (static::$dbQuery['where'] == '') {
|
||||
static::$dbQuery['where'] = "$column $operatorOrValue $value";
|
||||
} else {
|
||||
static::$querySelect['where'] .= " AND $column $operatorOrValue $value";
|
||||
static::$dbQuery['where'] .= " AND $column $operatorOrValue $value";
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -633,10 +702,10 @@ class Model
|
||||
$value = static::bind($value);
|
||||
}
|
||||
|
||||
if (static::$querySelect['where'] == '') {
|
||||
static::$querySelect['where'] = "$column $operatorOrValue $value";
|
||||
if (static::$dbQuery['where'] == '') {
|
||||
static::$dbQuery['where'] = "$column $operatorOrValue $value";
|
||||
} else {
|
||||
static::$querySelect['where'] .= " OR $column $operatorOrValue $value";
|
||||
static::$dbQuery['where'] .= " OR $column $operatorOrValue $value";
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -663,10 +732,10 @@ class Model
|
||||
}
|
||||
|
||||
$where = "$column IN (" . join(', ', $arrIn) . ")";
|
||||
if (static::$querySelect['where'] == '') {
|
||||
static::$querySelect['where'] = $where;
|
||||
if (static::$dbQuery['where'] == '') {
|
||||
static::$dbQuery['where'] = $where;
|
||||
} else {
|
||||
static::$querySelect['where'] .= " AND $where";
|
||||
static::$dbQuery['where'] .= " AND $where";
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -693,10 +762,10 @@ class Model
|
||||
}
|
||||
|
||||
$where = "$column NOT IN (" . join(', ', $arrIn) . ")";
|
||||
if (static::$querySelect['where'] == '') {
|
||||
static::$querySelect['where'] = $where;
|
||||
if (static::$dbQuery['where'] == '') {
|
||||
static::$dbQuery['where'] = $where;
|
||||
} else {
|
||||
static::$querySelect['where'] .= " AND $where";
|
||||
static::$dbQuery['where'] .= " AND $where";
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -787,7 +856,7 @@ class Model
|
||||
$operatorOrColumnB = '=';
|
||||
}
|
||||
|
||||
static::$querySelect['leftJoin'] .= ' LEFT JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
static::$dbQuery['leftJoin'] .= ' LEFT JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -822,13 +891,13 @@ class Model
|
||||
}
|
||||
|
||||
if (static::db()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'sqlite') {
|
||||
$currentTable = empty(static::$querySelect['from']) ?
|
||||
static::table() : static::$querySelect['from'];
|
||||
static::$querySelect['from'] = $table;
|
||||
$currentTable = empty(static::$dbQuery['from']) ?
|
||||
static::table() : static::$dbQuery['from'];
|
||||
static::$dbQuery['from'] = $table;
|
||||
return static::leftJoin($currentTable, $columnB, $operatorOrColumnB, $columnA);
|
||||
}
|
||||
|
||||
static::$querySelect['rightJoin'] .= ' RIGHT JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
static::$dbQuery['rightJoin'] .= ' RIGHT JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -862,7 +931,7 @@ class Model
|
||||
$operatorOrColumnB = '=';
|
||||
}
|
||||
|
||||
static::$querySelect['innerJoin'] .= ' INNER JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
static::$dbQuery['innerJoin'] .= ' INNER JOIN ' . $table . ' ON ' . "$columnA$operatorOrColumnB$columnB";
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -888,7 +957,7 @@ class Model
|
||||
public static function crossJoin(
|
||||
string $table,
|
||||
): static {
|
||||
static::$querySelect['crossJoin'] .= ' CROSS JOIN ' . $table;
|
||||
static::$dbQuery['crossJoin'] .= ' CROSS JOIN ' . $table;
|
||||
return new static();
|
||||
}
|
||||
|
||||
@@ -896,13 +965,13 @@ class Model
|
||||
* Defines GROUP BY in the SQL statement.
|
||||
*
|
||||
* @param array $columns
|
||||
* Columns to group by.
|
||||
* Columns to group by.
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public static function groupBy(string ...$columns): static
|
||||
{
|
||||
static::$querySelect['groupBy'] = join(', ', $columns);
|
||||
static::$dbQuery['groupBy'] = join(', ', $columns);
|
||||
return new static();
|
||||
}
|
||||
|
||||
@@ -920,9 +989,9 @@ class Model
|
||||
public static function limit(int $offsetOrQuantity, ?int $quantity = null): static
|
||||
{
|
||||
if (is_null($quantity)) {
|
||||
static::$querySelect['limit'] = $offsetOrQuantity;
|
||||
static::$dbQuery['limit'] = $offsetOrQuantity;
|
||||
} else {
|
||||
static::$querySelect['limit'] = $quantity . ' OFFSET ' . $offsetOrQuantity;
|
||||
static::$dbQuery['limit'] = $quantity . ' OFFSET ' . $offsetOrQuantity;
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -943,7 +1012,9 @@ class Model
|
||||
public static function orderBy(string $value, string $order = 'ASC'): static
|
||||
{
|
||||
if ($value == "RAND") {
|
||||
static::$querySelect['orderBy'] = 'RAND()';
|
||||
$random = static::db()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql' ? 'RAND()' : 'RANDOM()';
|
||||
static::$dbQuery['orderBy'] = $random;
|
||||
|
||||
return new static();
|
||||
}
|
||||
|
||||
@@ -951,7 +1022,7 @@ class Model
|
||||
$order = 'ASC';
|
||||
}
|
||||
|
||||
static::$querySelect['orderBy'] = $value . ' ' . $order;
|
||||
static::$dbQuery['orderBy'] = $value . ' ' . $order;
|
||||
|
||||
return new static();
|
||||
}
|
||||
@@ -972,25 +1043,25 @@ class Model
|
||||
{
|
||||
if (!$resetQuery) {
|
||||
$backup = [
|
||||
'select' => static::$querySelect['select'],
|
||||
'limit' => static::$querySelect['limit'],
|
||||
'orderBy' => static::$querySelect['orderBy'],
|
||||
'select' => static::$dbQuery['select'],
|
||||
'limit' => static::$dbQuery['limit'],
|
||||
'orderBy' => static::$dbQuery['orderBy'],
|
||||
];
|
||||
}
|
||||
|
||||
if ($useLimit && static::$querySelect['limit'] != '') {
|
||||
static::$querySelect['select'] = ['1'];
|
||||
static::$querySelect['orderBy'] = '';
|
||||
if ($useLimit && static::$dbQuery['limit'] != '') {
|
||||
static::$dbQuery['select'] = ['1'];
|
||||
static::$dbQuery['orderBy'] = '';
|
||||
|
||||
$sql = 'SELECT COUNT(1) AS quantity FROM (' . static::buildQuery() . ') AS counted';
|
||||
$queryResult = static::query($sql, $resetQuery);
|
||||
$result = $queryResult[0]['quantity'];
|
||||
} else {
|
||||
static::$querySelect['select'] = [
|
||||
"COUNT(" . static::table() . "." . static::$primaryKey . ") as quantity",
|
||||
static::$dbQuery['select'] = [
|
||||
"COUNT(" . static::table() . "." . static::$dbPrimaryKey . ") as quantity",
|
||||
];
|
||||
static::$querySelect['limit'] = '1';
|
||||
static::$querySelect['orderBy'] = '';
|
||||
static::$dbQuery['limit'] = '1';
|
||||
static::$dbQuery['orderBy'] = '';
|
||||
|
||||
$sql = static::buildQuery();
|
||||
$queryResult = static::query($sql, $resetQuery);
|
||||
@@ -998,9 +1069,9 @@ class Model
|
||||
}
|
||||
|
||||
if (!$resetQuery) {
|
||||
static::$querySelect['select'] = $backup['select'];
|
||||
static::$querySelect['limit'] = $backup['limit'];
|
||||
static::$querySelect['orderBy'] = $backup['orderBy'];
|
||||
static::$dbQuery['select'] = $backup['select'];
|
||||
static::$dbQuery['limit'] = $backup['limit'];
|
||||
static::$dbQuery['orderBy'] = $backup['orderBy'];
|
||||
}
|
||||
|
||||
return (int)$result;
|
||||
@@ -1016,7 +1087,7 @@ class Model
|
||||
*/
|
||||
public static function getById(mixed $id): ?static
|
||||
{
|
||||
return static::where(static::$primaryKey, $id)->getFirst();
|
||||
return static::where(static::$dbPrimaryKey, $id)->getFirst();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1033,8 +1104,18 @@ class Model
|
||||
public static function search(string $search, ?array $in = null): static
|
||||
{
|
||||
if ($in == null) {
|
||||
$className = get_called_class();
|
||||
$in = array_keys((new $className())->getVars());
|
||||
$in = [];
|
||||
$reflection = new \ReflectionClass(get_called_class());
|
||||
|
||||
foreach ($reflection->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
|
||||
if (!in_array($property->getName(), static::$dbIgnoreSave)) {
|
||||
$in[] = static::camelCaseToSnakeCase($property->getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($in)) {
|
||||
return new static();
|
||||
}
|
||||
|
||||
$search = static::bind($search);
|
||||
@@ -1050,10 +1131,10 @@ class Model
|
||||
}
|
||||
}
|
||||
|
||||
if (static::$querySelect['where'] == '') {
|
||||
static::$querySelect['where'] = join(' OR ', $where);
|
||||
if (static::$dbQuery['where'] == '') {
|
||||
static::$dbQuery['where'] = join(' OR ', $where);
|
||||
} else {
|
||||
static::$querySelect['where'] = static::$querySelect['where'] . ' AND (' . join(' OR ', $where) . ')';
|
||||
static::$dbQuery['where'] = static::$dbQuery['where'] . ' AND (' . join(' OR ', $where) . ')';
|
||||
}
|
||||
|
||||
return new static();
|
||||
@@ -1117,22 +1198,4 @@ class Model
|
||||
|
||||
return $instances;
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows defining an attribute's value as null.
|
||||
* Only works for updating an element in the DB, not for inserting.
|
||||
*
|
||||
* @param array $attributes
|
||||
* Attribute or array of attributes that will be set to null.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function setNull(string ...$attributes): void
|
||||
{
|
||||
foreach ($attributes as $att) {
|
||||
if (!in_array($att, $this->toNull)) {
|
||||
$this->toNull[] = $att;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -50,9 +50,9 @@ class Neuron
|
||||
* It returns null instead of triggering an E_NOTICE.
|
||||
*
|
||||
* @param string $index The name of the property being accessed.
|
||||
* @return null Always returns null for undefined properties.
|
||||
* @return null Always returns null for undefined properties.
|
||||
*/
|
||||
public function __get(string $index): null
|
||||
public function __get(string $index)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
+48
-17
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Libs;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Request - DuckBrain
|
||||
*
|
||||
@@ -59,39 +61,48 @@ class Request extends Neuron
|
||||
}
|
||||
|
||||
// Run configured validations
|
||||
if (!$this->validate()) {
|
||||
exit();
|
||||
}
|
||||
$this->validate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the configured validation.
|
||||
*
|
||||
* @return bool
|
||||
* On failure the single error message is built with Validator::message()
|
||||
* and handed to onInvalid(), which throws by default: failures travel up
|
||||
* as exceptions instead of answering HTTP here.
|
||||
*
|
||||
* @return void
|
||||
* @throws Exception When a configured rule fails.
|
||||
*/
|
||||
public function validate(): bool
|
||||
public function validate(): void
|
||||
{
|
||||
$actual = match ($_SERVER['REQUEST_METHOD']) {
|
||||
'POST', 'PUT', 'PATCH', 'DELETE' => $this->{strtolower($_SERVER['REQUEST_METHOD'])},
|
||||
default => $this->get
|
||||
};
|
||||
|
||||
// Merge uploaded files ($_FILES) into the body data set so the file rules
|
||||
// (file/image/mimes and the routed min/max/required...) can validate
|
||||
// uploads through a Request. $this->post is left untouched.
|
||||
$body = empty($_FILES)
|
||||
? $actual
|
||||
: new Neuron(array_merge(get_object_vars($actual), $_FILES));
|
||||
|
||||
if (
|
||||
Validator::validateList(static::paramRules(), $this->params) &&
|
||||
Validator::validateList(static::getRules(), $this->get) &&
|
||||
Validator::validateList(static::rules(), $actual)
|
||||
Validator::validateList(static::rules(), $body)
|
||||
) {
|
||||
return true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (isset(static::messages()[Validator::$lastFailed])) {
|
||||
$error = static::messages()[Validator::$lastFailed];
|
||||
} else {
|
||||
$error = 'Error: validation failed of ' . preg_replace('/\./', ' as ', Validator::$lastFailed, 1);
|
||||
}
|
||||
$error = Validator::message(
|
||||
Validator::$lastFailed,
|
||||
static::messages(),
|
||||
static::attributes()
|
||||
);
|
||||
|
||||
static::onInvalid($error);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,16 +145,36 @@ class Request extends Neuron
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Human-readable names for the fields.
|
||||
*
|
||||
* Forwarded to Validator::message() so the :attribute marker in the error
|
||||
* text can be replaced with a friendlier name (e.g. "edad" => "la edad").
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function attributes(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to execute when an invalid value has been detected.
|
||||
*
|
||||
* The default implementation always throws a generic \Exception carrying
|
||||
* the single error message and HTTP 422 as its code; the framework's
|
||||
* exception boundary (Router::apply) renders the response. Override it to
|
||||
* throw a more specific exception type instead. The never return type is
|
||||
* the contract: an override that returned would let the request continue
|
||||
* with invalid data, so PHP rejects such an override at compile time.
|
||||
*
|
||||
* @param string $error
|
||||
*
|
||||
* @return void
|
||||
* @return never
|
||||
* @throws Exception
|
||||
*/
|
||||
public function onInvalid(string $error): void
|
||||
public function onInvalid(string $error): never
|
||||
{
|
||||
http_response_code(422);
|
||||
print($error);
|
||||
throw new Exception($error, 422);
|
||||
}
|
||||
}
|
||||
|
||||
+90
-33
@@ -50,7 +50,7 @@ class Router
|
||||
*
|
||||
* @var callable $notFoundCallback
|
||||
*/
|
||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||
public static $notFoundCallback = 'Libs\Router::defaultNotFound';
|
||||
|
||||
/**
|
||||
* Default callback function for when
|
||||
@@ -64,6 +64,54 @@ class Router
|
||||
echo '<h2 style="text-align: center;margin: 25px 0px;">Error 404 - Page Not Found</h2>';
|
||||
}
|
||||
|
||||
/**
|
||||
* The callback function to be executed when the router's boundary
|
||||
* catches an exception thrown anywhere in the matched route chain.
|
||||
* It receives the exception as a named argument: the handler must
|
||||
* declare its parameter as $exception (typeable as \Throwable).
|
||||
*
|
||||
* @var callable $exceptionCallback
|
||||
*/
|
||||
public static $exceptionCallback = 'Libs\Router::defaultException';
|
||||
|
||||
/**
|
||||
* Default callback function for exception responses.
|
||||
*
|
||||
* The HTTP status comes from the exception's code only when it is an
|
||||
* integer in the 400-599 range; anything else (0, arbitrary codes, the
|
||||
* SQLSTATE string carried by PDOException) answers 500. The body is
|
||||
* negotiated from the request's Accept header: JSON when the client asks
|
||||
* for application/json, plain text otherwise. The trace is serialized
|
||||
* from getTraceAsString() because json_encode() of a Throwable yields an
|
||||
* empty object: its properties are protected.
|
||||
*
|
||||
* @param \Throwable $exception
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function defaultException(\Throwable $exception): void
|
||||
{
|
||||
$code = $exception->getCode();
|
||||
http_response_code(is_int($code) && $code >= 400 && $code <= 599 ? $code : 500);
|
||||
|
||||
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
|
||||
|
||||
if (str_contains($accept, 'application/json')) {
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode([
|
||||
'error' => $exception->getMessage(),
|
||||
'exception' => get_class($exception),
|
||||
'file' => $exception->getFile(),
|
||||
'line' => $exception->getLine(),
|
||||
'trace' => explode(PHP_EOL, $exception->getTraceAsString()),
|
||||
]));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
print($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
|
||||
}
|
||||
|
||||
/**
|
||||
* __construct
|
||||
*/
|
||||
@@ -136,7 +184,6 @@ class Router
|
||||
public static function redirect(string $path): void
|
||||
{
|
||||
header('Location: ' . static::basePath() . ltrim($path, '/'));
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -363,50 +410,60 @@ class Router
|
||||
/**
|
||||
* Applies the route configuration.
|
||||
*
|
||||
* This method is the framework's error boundary: any \Throwable thrown
|
||||
* while running the matched route's callback chain, while printing the
|
||||
* returned data, or while resolving the not-found callback is caught
|
||||
* here and rendered through $exceptionCallback. A failing handler is
|
||||
* deliberately left uncaught (double failure falls back to PHP itself).
|
||||
*
|
||||
* @param string|null $path (optional) Path to use. If not defined, it detects the current path.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function apply(?string $path = null): void
|
||||
{
|
||||
$path = $path ?? static::currentPath();
|
||||
$routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method
|
||||
'POST' => static::$post,
|
||||
'PUT' => static::$put,
|
||||
'PATCH' => static::$patch,
|
||||
'DELETE' => static::$delete,
|
||||
default => static::$get
|
||||
};
|
||||
try {
|
||||
$path = $path ?? static::currentPath();
|
||||
$routers = match ($_SERVER['REQUEST_METHOD']) { // Selects an array of routers based on the method
|
||||
'POST' => static::$post,
|
||||
'PUT' => static::$put,
|
||||
'PATCH' => static::$patch,
|
||||
'DELETE' => static::$delete,
|
||||
default => static::$get
|
||||
};
|
||||
|
||||
foreach ($routers as $router) { // Checks all routers to see if they match the current path
|
||||
if (preg_match_all('/^' . $router['path'] . '\/?$/si', $path, $matches, PREG_PATTERN_ORDER)) {
|
||||
unset($matches[0]);
|
||||
foreach ($routers as $router) { // Checks all routers to see if they match the current path
|
||||
if (preg_match_all('/^' . $router['path'] . '\/?$/si', $path, $matches, PREG_PATTERN_ORDER)) {
|
||||
unset($matches[0]);
|
||||
|
||||
// Checking and storing the variable parameters of the route
|
||||
if (isset($matches[1])) {
|
||||
static::$params = new Neuron();
|
||||
foreach ($matches as $index => $match) {
|
||||
$paramName = $router['paramNames'][$index - 1];
|
||||
static::$params->{$paramName} = urldecode($match[0]);
|
||||
// Checking and storing the variable parameters of the route
|
||||
if (isset($matches[1])) {
|
||||
static::$params = new Neuron();
|
||||
foreach ($matches as $index => $match) {
|
||||
$paramName = $router['paramNames'][$index - 1];
|
||||
static::$params->{$paramName} = urldecode($match[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Processes the callback queue
|
||||
foreach (array_reverse($router['callback']) as $callback) {
|
||||
$data = Synapsis::resolve($callback);
|
||||
}
|
||||
// Processes the callback queue
|
||||
foreach (array_reverse($router['callback']) as $callback) {
|
||||
$data = Synapsis::resolve($callback);
|
||||
}
|
||||
|
||||
// By default, prints as JSON if something is returned
|
||||
if (isset($data)) {
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($data));
|
||||
}
|
||||
// By default, prints as JSON if something is returned
|
||||
if (isset($data)) {
|
||||
header('Content-Type: application/json');
|
||||
print(json_encode($data));
|
||||
}
|
||||
|
||||
return;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no router matches, call $notFoundCallBack
|
||||
Synapsis::resolve(static::$notFoundCallback);
|
||||
// If no router matches, call $notFoundCallBack
|
||||
Synapsis::resolve(static::$notFoundCallback);
|
||||
} catch (\Throwable $exception) {
|
||||
Synapsis::resolve(static::$exceptionCallback, ['exception' => $exception]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+22
-5
@@ -65,12 +65,14 @@ class Synapsis
|
||||
/**
|
||||
* Resolves and injects dependencies for a callable and returns its result.
|
||||
*
|
||||
* @param callable $action
|
||||
* @param callable $action
|
||||
* @param array<string, mixed> $named Associative array of values injected into the callable's
|
||||
* parameters by exact name match. Consumed in resolveParameterValues().
|
||||
*
|
||||
* @return mixed
|
||||
* @throws Exception If an unhandled callable type is provided.
|
||||
*/
|
||||
public static function resolve(callable $action): mixed
|
||||
public static function resolve(callable $action, array $named = []): mixed
|
||||
{
|
||||
if ($action instanceof Closure) { // If it's an anonymous function
|
||||
$reflectionCallback = new ReflectionFunction($action);
|
||||
@@ -90,7 +92,7 @@ class Synapsis
|
||||
// Get the parameters
|
||||
return call_user_func_array(
|
||||
$action,
|
||||
static::resolveParameterValues($reflectionCallback->getParameters())
|
||||
static::resolveParameterValues($reflectionCallback->getParameters(), $named)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -132,14 +134,27 @@ class Synapsis
|
||||
* Resolves parameter values by injecting dependencies.
|
||||
*
|
||||
* @param array<ReflectionParameter> $parameters
|
||||
* @param array<string, mixed> $named
|
||||
* Values injected into parameters whose name matches the key,
|
||||
* taking precedence over optional defaults and DI resolution.
|
||||
* Keys matching no parameter are ignored.
|
||||
*
|
||||
* @return array<mixed>
|
||||
* @throws Exception If a primitive parameter does not have a default value.
|
||||
*/
|
||||
public static function resolveParameterValues(array $parameters): array
|
||||
public static function resolveParameterValues(array $parameters, array $named = []): array
|
||||
{
|
||||
$values = [];
|
||||
foreach ($parameters as $parameter) {
|
||||
if ($parameter->isVariadic()) { // Skip variatic parameters
|
||||
continue;
|
||||
}
|
||||
|
||||
if (array_key_exists($parameter->getName(), $named)) { // Named values win over defaults and DI
|
||||
$values[] = $named[$parameter->getName()];
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($parameter->isOptional()) { // Always use the default value first
|
||||
$values[] = $parameter->getDefaultValue();
|
||||
continue;
|
||||
@@ -148,7 +163,9 @@ class Synapsis
|
||||
$paramType = $parameter->getType();
|
||||
if ($paramType === null) {
|
||||
// If no type is declared, and it's not optional, we cannot resolve it.
|
||||
throw new Exception('Untyped parameters expect at least a default value or must be optional.');
|
||||
throw new Exception(
|
||||
"Untyped parameter '{$parameter}' expect at least a default value or must be optional."
|
||||
);
|
||||
}
|
||||
|
||||
if ($paramType->isBuiltin()) {
|
||||
|
||||
+1075
-32
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user