docs: Improve documentation and translate comments to English

This commit is contained in:
kj
2025-10-10 21:18:22 -03:00
parent 674c9d5ff4
commit 7f62e06ff9
8 changed files with 369 additions and 307 deletions

View File

@@ -12,23 +12,50 @@ use ReflectionProperty;
/**
* Model - DuckBrain
*
* Modelo ORM para objetos que hagan uso de una base de datos.
* Depende de Libs\Database y hace uso de las constantes
* DB_TYPE, DB_HOST, DB_NAME, DB_USER y DB_PASS.
* ORM Model for database-backed objects.
* Depends on Libs\Database and uses constants
* DB_TYPE, DB_HOST, DB_NAME, DB_USER, and DB_PASS.
*
* @author KJ
* @website https://kj2.me
* @licence MIT
* @license MIT
*/
#[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';
/**
* @var array Attributes to ignore when saving to the database.
*/
protected static array $ignoreSave = ['id'];
/**
* @var array Attributes that should be explicitly saved, even if private/protected.
*/
protected static array $forceSave = [];
/**
* @var string The database table name.
*/
protected static string $table;
/**
* @var array Variables for PDO prepared statements.
*/
protected static array $queryVars = [];
/**
* @var array Current SELECT query components.
*/
protected static array $querySelect = [
'select' => ['*'],
'where' => '',
@@ -42,7 +69,7 @@ class Model
];
/**
* Sirve para obtener la instancia de la base de datos.
* Retrieves the database instance.
*
* @return PDO
*/
@@ -65,8 +92,8 @@ class Model
}
/**
* Ejecuta PDO::beginTransaction para iniciar una transacción.
* Más info: https://www.php.net/manual/es/pdo.begintransaction.php
* Executes PDO::beginTransaction to start a transaction.
* More info: https://www.php.net/manual/es/pdo.begintransaction.php (Spanish, will keep for context)
*
* @return bool
*/
@@ -76,8 +103,8 @@ class Model
}
/**
* Ejecuta PDO::rollBack para deshacher los cambios de una transacción.
* Más info: https://www.php.net/manual/es/pdo.rollback.php
* Executes PDO::rollBack to undo changes in a transaction.
* More info: https://www.php.net/manual/es/pdo.rollback.php (Spanish, will keep for context)
*
* @return bool
*/
@@ -91,8 +118,8 @@ class Model
}
/**
* Ejecuta PDO::commit para consignar una transacción.
* Más info: https://www.php.net/manual/es/pdo.commit.php
* Executes PDO::commit to commit a transaction.
* More info: https://www.php.net/manual/es/pdo.commit.php (Spanish, will keep for context)
*
* @return bool
*/
@@ -106,21 +133,21 @@ class Model
}
/**
* Ejecuta una sentencia SQL en la base de datos.
* Executes an SQL statement in the database.
*
* @param string $query
* Contiene la sentencia SQL que se desea ejecutar.
* Contains the SQL statement to be executed.
*
* @throws Exception
* En caso de que la sentencia SQL falle, devolverá un error en
* pantalla y hará rolllback en caso de estar dentro de una
* transacción (ver método beginTransacction).
* If the SQL statement fails, it will throw an error
* and perform a rollback if currently within a transaction
* (see beginTransaction method).
*
* @param bool $resetQuery
* Indica si el query debe reiniciarse o no (por defecto es true).
* Indicates whether the query should be reset (defaults to true).
*
* @return array
* Contiene el resultado de la llamada SQL .
* Contains the result of the SQL call.
*/
protected static function query(string $query, bool $resetQuery = true): array
{
@@ -154,7 +181,7 @@ class Model
}
/**
* Reinicia la configuración de la sentencia SQL.
* Resets the SQL query configuration.
* @return void
*/
protected static function resetQuery(): void
@@ -174,11 +201,11 @@ class Model
}
/**
* Construye la sentencia SQL a partir static::$querySelect y una vez
* construída, llama a resetQuery.
* Builds the SQL statement from static::$querySelect and, once
* built, calls resetQuery.
*
* @return string
* Contiene la sentencia SQL.
* Contains the SQL statement.
*/
protected static function buildQuery(): string
{
@@ -223,14 +250,14 @@ class Model
/**
* Configura $queryVars para vincular un valor a un
* parámetro de sustitución y devuelve este último.
* Configures $queryVars to bind a value to a
* substitution parameter and returns the latter.
*
* @param string $value
* Valor a vincular.
* Value to bind.
*
* @return string
* Parámetro de sustitución.
* Substitution parameter.
*/
private static function bindValue(string $value): string
{
@@ -240,14 +267,14 @@ class Model
}
/**
* Crea una instancia del objeto actual a partir de un arreglo.
* Creates an instance of the current object from an array.
*
* @param mixed $elem
* Puede recibir un arreglo o un objeto que contiene los valores
* que tendrán sus atributos.
* Can receive an array or an object containing the values
* that its attributes will have.
*
* @return static
* Retorna un objeto de la clase actual.
* Returns an object of the current class.
*/
protected static function getInstance(array $elem = []): static
{
@@ -276,13 +303,12 @@ class Model
}
/**
* Devuelve los atributos a guardar de la case actual.
* Los atributos serán aquellos que seran public y
* no esten excluidos en static::$ignoresave y aquellos
* que sean private o protected pero estén en static::$forceSave.
* Returns the attributes to be saved for the current class.
* Attributes will be those that are public and not excluded in static::$ignoreSave,
* and those that are private or protected but are in static::$forceSave.
*
* @return array
* Contiene los atributos indexados del objeto actual.
* Contains the indexed attributes of the current object.
*/
protected function getVars(): array
{
@@ -316,7 +342,7 @@ class Model
}
/**
* Devuelve el nombre de la clase actual aunque sea una clase extendida.
* Returns the name of the current class, even if it's an extended class.
*
* @return string
*
@@ -330,9 +356,9 @@ class Model
}
/**
* Construye (a partir del nombre de la clase y el sufijo en static::$tableSufix)
* y/o develve el nombre de la tabla de la BD en la que se alojará o
* se aloja el objeto actual.
* Constructs (from the class name and the suffix in static::$tableSufix)
* and/or returns the name of the DB table where the current object will be
* or is stored.
*
* @return string
*/
@@ -346,7 +372,7 @@ class Model
}
/**
* Convierte de lowerCamelCase a snake_case
* Converts from lowerCamelCase to snake_case.
*
* @param string $string
*
@@ -364,7 +390,7 @@ class Model
}
/**
* Convierte de snake_case a lowerCamelCase
* Converts from snake_case to lowerCamelCase.
*
* @param string $string
*
@@ -378,7 +404,7 @@ class Model
}
/**
* Actualiza los valores en la BD con los valores del objeto actual.
* Updates the values in the database with the current object's values.
* @return void
*/
protected function update(): void
@@ -408,14 +434,16 @@ class Model
}
/**
* Inserta una nueva fila en la base de datos a partir del
* objeto actual.
* Inserts a new row into the database from the
* current object.
* @return void
*/
protected function add(): void
{
$db = static::db();
$atts = $this->getVars();
$into = [];
$values = [];
foreach ($atts as $key => $value) {
if (isset($value)) {
@@ -434,8 +462,8 @@ class Model
}
/**
* Revisa si el objeto a guardar es nuevo o no y según el resultado
* llama a update para actualizar o add para insertar una nueva fila.
* 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
@@ -449,7 +477,7 @@ class Model
}
/**
* Elimina el objeto actual de la base de datos.
* Deletes the current object from the database.
* @return void
*/
public function delete(): void
@@ -463,10 +491,10 @@ class Model
}
/**
* Define SELECT en la sentencia SQL.
* Defines SELECT in the SQL statement.
*
* @param array $columns
* Columnas que se selecionarán en la consulta SQL.
* Columns to be selected in the SQL query.
*
* @return static
*/
@@ -478,10 +506,10 @@ class Model
}
/**
* Define FROM en la sentencia SQL.
* Defines FROM in the SQL statement.
*
* @param array $tables
* Tablas que se selecionarán en la consulta SQL.
* Tables to be selected in the SQL query.
*
* @return static
*/
@@ -493,20 +521,20 @@ class Model
}
/**
* Define el WHERE en la sentencia SQL.
* Defines the WHERE clause in the SQL statement.
*
* @param string $column
* La columna a comparar.
* The column to compare.
*
* @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina.
* The operator or the value to compare as equal if $value is not defined.
*
* @param string|null $value
* (opcional) El valor a comparar en la columna.
* (Optional) The value to compare against the column.
*
* @param bool $no_filter
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
* contra ataques SQLI (por defeco es false).
* (Optional) Used when $value is a column or a value that does not require
* filtering against SQL injection attacks (defaults to false).
*
* @return static
*/
@@ -525,20 +553,20 @@ class Model
}
/**
* Define AND en la sentencia SQL (se puede anidar).
* Defines AND in the SQL statement (can be nested).
*
* @param string $column
* La columna a comparar.
* The column to compare.
*
* @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina.
* The operator or the value to compare as equal if $value is not defined.
*
* @param string|null $value
* (opcional) El valor el valor a comparar en la columna.
* (Optional) The value to compare against the column.
*
* @param bool $no_filter
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
* contra ataques SQLI (por defecto es false).
* (Optional) Used when $value is a column or a value that does not require
* filtering against SQL injection attacks (defaults to false).
*
* @return static
*/
@@ -567,20 +595,20 @@ class Model
}
/**
* Define OR en la sentencia SQL (se puede anidar).
* Defines OR in the SQL statement (can be nested).
*
* @param string $column
* La columna a comparar.
* The column to compare.
*
* @param string $operatorOrValue
* El operador o el valor a comparar como igual en caso de que $value no se defina.
* The operator or the value to compare as equal if $value is not defined.
*
* @param string|null $value
* (opcional) El valor el valor a comparar en la columna.
* (Optional) The value to compare against the column.
*
* @param bool $no_filter
* (opcional) Se usa cuando $value es una columna o un valor que no requiere filtros
* contra ataques SQLI (por defecto es false).
* (Optional) Used when $value is a column or a value that does not require
* filtering against SQL injection attacks (defaults to false).
*
* @return static
*/
@@ -609,16 +637,16 @@ class Model
}
/**
* Define WHERE usando IN en la sentencia SQL.
* Defines WHERE using IN in the SQL statement.
*
* @param string $column
* La columna a comparar.
* The column to compare.
*
* @param array $arr
* Arreglo con todos los valores a comparar con la columna.
* Array with all values to compare against the column.
*
* @param bool $in
* Define si se tienen que comprobar negativa o positivamente.
* Defines whether to check positively (IN) or negatively (NOT IN).
*
* @return static
*/
@@ -648,20 +676,20 @@ class Model
}
/**
* Define LEFT JOIN en la sentencia SQL.
* Defines LEFT JOIN in the SQL statement.
*
* @param string $table
* Tabla que se va a juntar a la del objeto actual.
* Table to join with the current object's table.
*
* @param string $columnA
* Columna a comparar para hacer el join.
* Column to compare for the join.
*
* @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer
* el join en caso de que $columnB no se defina.
* Operator or column to compare as equal for the join
* if $columnB is not defined.
*
* @param string|null $columnB
* (opcional) Columna a comparar para hacer el join.
* (Optional) Column to compare for the join.
*
* @return static
*/
@@ -682,20 +710,20 @@ class Model
}
/**
* Define RIGHT JOIN en la sentencia SQL.
* Defines RIGHT JOIN in the SQL statement.
*
* @param string $table
* Tabla que se va a juntar a la del objeto actual.
* Table to join with the current object's table.
*
* @param string $columnA
* Columna a comparar para hacer el join.
* Column to compare for the join.
*
* @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer
* el join en caso de que $columnB no se defina.
* Operator or column to compare as equal for the join
* if $columnB is not defined.
*
* @param string|null $columnB
* (opcional) Columna a comparar para hacer el join.
* (Optional) Column to compare for the join.
*
* @return static
*/
@@ -716,20 +744,20 @@ class Model
}
/**
* Define INNER JOIN en la sentencia SQL.
* Defines INNER JOIN in the SQL statement.
*
* @param string $table
* Tabla que se va a juntar a la del objeto actual.
* Table to join with the current object's table.
*
* @param string $columnA
* Columna a comparar para hacer el join.
* Column to compare for the join.
*
* @param string $operatorOrColumnB
* Operador o columna a comparar como igual para hacer
* el join en caso de que $columnB no se defina.
* Operator or column to compare as equal for the join
* if $columnB is not defined.
*
* @param string|null $columnB
* (opcional) Columna a comparar para hacer el join.
* (Optional) Column to compare for the join.
*
* @return static
*/
@@ -750,10 +778,10 @@ class Model
}
/**
* Define GROUP BY en la sentencia SQL.
* Defines GROUP BY in the SQL statement.
*
* @param array $arr
* Columnas por las que se agrupará.
* Columns to group by.
*
* @return static
*/
@@ -764,13 +792,13 @@ class Model
}
/**
* Define LIMIT en la sentencia SQL.
* Defines LIMIT in the SQL statement.
*
* @param int $offsetOrQuantity
* Define el las filas a ignorar o la cantidad a tomar en
* caso de que $quantity no esté definido.
* @param int $quantity
* Define la cantidad máxima de filas a tomar.
* Defines the rows to skip or the quantity to take
* if $quantity is not defined.
* @param int|null $quantity
* (Optional) Defines the maximum number of rows to take.
*
* @return static
*/
@@ -786,14 +814,14 @@ class Model
}
/**
* Define ORDER BY en la sentencia SQL.
* Defines ORDER BY in the SQL statement.
*
* @param string $value
* Columna por la que se ordenará.
* Column to order by.
*
* @param string $order
* (opcional) Define si el orden será de manera ascendente (ASC),
* descendente (DESC) o aleatorio (RAND).
* (Optional) Defines whether the order will be ascending (ASC),
* descending (DESC), or random (RAND).
*
* @return static
*/
@@ -814,14 +842,14 @@ class Model
}
/**
* Retorna la cantidad de filas que hay en un query.
* Returns the number of rows in a query.
*
* @param bool $resetQuery
* (opcional) Indica si el query debe reiniciarse o no (por defecto es true).
* (Optional) Indicates whether the query should be reset (defaults to true).
*
* @param bool $useLimit
* (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).
* (Optional) Allows using limit to establish an initial and final maximum for counting.
* Requires the limit to have been defined beforehand (defaults to false).
*
* @return int
*/
@@ -860,12 +888,12 @@ class Model
static::$querySelect['orderBy'] = $backup['orderBy'];
}
return $result;
return (int)$result;
}
/**
* Obtiene una instancia según su primary key (generalmente id).
* Si no encuentra una instancia, devuelve nulo.
* Retrieves an instance by its primary key (usually 'id').
* If no instance is found, returns null.
*
* @param mixed $id
*
@@ -877,13 +905,13 @@ class Model
}
/**
* Realiza una búsqueda en la tabla de la instancia actual.
* Performs a search in the current instance's table.
*
* @param string $search
* Contenido a buscar.
* Content to search for.
*
* @param array|null $in
* (opcional) Columnas en las que se va a buscar (null para buscar en todas).
* (Optional) Columns to search within (null to search all).
*
* @return static
*/
@@ -918,13 +946,13 @@ class Model
}
/**
* Obtener los resultados de la consulta SQL.
* Retrieves the results of the SQL query.
*
* @param bool $resetQuery
* (opcional) Indica si el query debe reiniciarse o no (por defecto es true).
* (Optional) Indicates whether the query should be reset (defaults to true).
*
* @return array<static>
* Arreglo con instancias del la clase actual resultantes del query.
* Array with instances of the current class resulting from the query.
*/
public static function get(bool $resetQuery = true): array
{
@@ -941,13 +969,13 @@ class Model
}
/**
* El primer elemento de la consulta SQL.
* Retrieves the first element from the SQL query result.
*
* @param bool $resetQuery
* (opcional) Indica si el query debe reiniciarse o no (por defecto es true).
* (Optional) Indicates whether the query should be reset (defaults to true).
*
* @return static|null
* Puede retornar una instancia de la clase actual o null.
* Can return an instance of the current class or null.
*/
public static function getFirst(bool $resetQuery = true): ?static
{
@@ -957,10 +985,10 @@ class Model
}
/**
* Obtener todos los elementos del la tabla de la instancia actual.
* Retrieves all elements from the current instance's table.
*
* @return array<static>
* Contiene un arreglo de instancias de la clase actual.
* Contains an array of instances of the current class.
*/
public static function all(): array
{
@@ -977,11 +1005,11 @@ class Model
}
/**
* Permite definir como nulo el valor de un atributo.
* Sólo funciona para actualizar un elemento de la BD, no para insertar.
* Allows defining an attribute's value as null.
* Only works for updating an element in the DB, not for inserting.
*
* @param array $attributes
* Atributo o arreglo de atributos que se definirán como nulos.
* Attribute or array of attributes that will be set to null.
*
* @return void
*/