VanguardAI/app/Repositories/BaseRepository.php
2024-10-27 12:50:51 -06:00

197 lines
4.7 KiB
PHP

<?php
namespace App\Repositories;
use App\Core\Database;
use App\Entities\BaseEntity;
use Exception;
use PDOStatement;
class BaseRepository
{
protected $db;
protected string $table;
protected string $primaryKey;
protected string $entityClass;
/**
* Constructor
*
* @param Database $database Conexión a la base de datos.
* @param string $table Nombre de la tabla en la base de datos.
* @param string $entityClass Clase de la entidad (debe extender BaseEntity).
*
* @throws Exception Si la clase de entidad proporcionada no es válida.
*/
public function __construct(Database $database, string $table, string $entityClass)
{
$this->db = $database->getConnection();
$this->table = $table;
if (!is_subclass_of($entityClass, BaseEntity::class)) {
throw new Exception("La clase de entidad debe extender de BaseEntity.");
}
$this->entityClass = $entityClass;
$this->primaryKey = $entityClass::getPrimaryKey();
}
/**
* Obtiene todas las filas de la tabla.
*
* @return array
*/
public function getAll(): array
{
return $this->db->select($this->table, "*");
}
/**
* Encuentra una fila por un campo específico.
*
* @param string $field Campo por el cual buscar.
* @param mixed $value Valor del campo.
*
* @return array|null
*/
public function findBy(string $field, $value): ?array
{
return $this->db->get($this->table, "*", [$field => $value]);
}
/**
* Encuentra una fila por su ID.
*
* @param mixed $id Identificador de la fila.
*
* @return array|null
*/
public function findById($id): ?array
{
return $this->db->get($this->table, "*", [$this->primaryKey => $id]);
}
/**
* Inserta una fila en la tabla.
*
* @param array $data Datos a insertar.
*
* @return bool|int
*/
public function insert(array $data): int|false
{
try {
$this->db->insert($this->table, $data);
$lastInsertId = (int) $this->db->id();
if ($lastInsertId) {
return $lastInsertId;
} else {
error_log("Error al insertar en la tabla {$this->table}: " . print_r($this->db->error(), true));
return false;
}
} catch (Exception $e) {
// Registra el error de la excepción
error_log("Excepción al insertar en la tabla {$this->table}: " . $e->getMessage());
return false;
}
}
/**
* Actualiza una fila por su ID.
*
* @param mixed $id Identificador de la fila a actualizar.
* @param array $data Datos a actualizar.
*
* @return bool
*/
public function update($id, array $data): bool
{
return $this->db->update($this->table, $data, [
$this->primaryKey => $id,
])->rowCount() > 0;
}
/**
* Elimina una fila por su ID.
*
* @param mixed $id Identificador de la fila a eliminar.
*
* @return bool
*/
public function delete($id): bool
{
return $this->db->delete($this->table, [$this->primaryKey => $id])->rowCount() > 0;
}
/**
* Marca una fila como inactiva (soft delete).
*
* @param mixed $id Identificador de la fila.
*
* @return bool
*/
public function deleteActive($id): bool
{
return $this->db->update(
$this->table,
["active" => false],
[$this->primaryKey => $id]
)->rowCount() > 0;
}
/**
* Obtiene una lista paginada de filas.
*
* @param int $page Número de página.
* @param int $perPage Número de filas por página.
*
* @return array
*/
public function getPaginated(int $page, int $perPage): array
{
$perPage = min($perPage, 100);
$offset = ($page - 1) * $perPage;
return $this->db->select($this->table, "*", [
"LIMIT" => [$offset, $perPage],
]);
}
/**
* Cuenta el total de filas en la tabla.
*
* @return int
*/
public function countAll(): int
{
return $this->db->count($this->table);
}
/**
* Inicia una transacción.
*/
public function beginTransaction()
{
$this->db->pdo->beginTransaction();
}
/**
* Confirma la transacción.
*/
public function commit()
{
$this->db->pdo->commit();
}
/**
* Revierte la transacción.
*/
public function rollBack()
{
if ($this->db->pdo->inTransaction()) {
$this->db->pdo->rollBack();
}
}
}