Files
api/traits/db_object_t.php
T
2024-12-16 08:54:03 +01:00

172 lines
5.4 KiB
PHP

<?php
namespace traits;
use classes\response;
use Exception;
trait db_object_t
{
private string $table; // The table of the objects in the database (e.g. users)
public int $id; // The id of the object in the database
public function __construct()
{
$this->structure();
}
public function __toString(): string
{
// Return the object as a string
return json_encode($this->getArray());
}
/**
* Set the table of the objects in the database
* @param string $table The table of the objects in the database
*/
public function setTable(string $table): void
{
$this->table = $table;
}
/**
* Structure: Define the table and fields of the objects in the database
*/
public function structure(): void
{
// Define the table and fields of the objects in the database
}
/**
* Get current object row as an array
* @return array The current object row as an array
* @throws Exception If object not found
*/
public function getArray(): array
{
// Get the object from the database
global $db;
// Check if the id is set, if not throw an exception
if (!isset($this->id)) {
throw new Exception('Object not found');
}
$id = $this->id;
$sql = "SELECT * FROM $this->table WHERE id = $id";
$result = $db->query($sql);
return $db->fetch_assoc($result);
}
/**
* List ALL objects in the table
* @return array The list of objects in the table
*/
public function listObjects(): array
{
global $db;
$sql = "SELECT * FROM $this->table";
$result = $db->query($sql);
return $db->fetch_all($result);
}
/**
* List objects in the table with pagination
* @param int $page The page number
* @param int $limit The number of objects per page
* @return array The list of objects in the table
*/
public function listObjectsWithPagination(int $page, int $limit, string $search = null, array $filters = null): array
{
global /** @var response $response */
$db, $response;
$offset = ($page - 1) * $limit;
// Get all the fields of the table
$sql = "SHOW COLUMNS FROM $this->table";
$result = $db->query($sql);
$fields = $db->fetch_all($result);
$searchfields = [];
foreach ($fields as $field) {
$searchfields[] = $field['Field'];
}
// Search for any similarities to the search query (Not case sensitive)
$searchQuery = '';
if ($search) {
$searchQuery = 'WHERE ';
$search = strtolower($search);
$searchQuery .= '(';
foreach ($searchfields as $field) {
$searchQuery .= "LOWER($field) LIKE '%$search%' OR ";
}
$searchQuery = substr($searchQuery, 0, -4);
$searchQuery .= ')';
}
// Filter the objects
if ($filters) {
if ($searchQuery) {
$searchQuery .= ' AND ';
} else {
$searchQuery = 'WHERE ';
}
foreach ($filters as $field => $value) {
$searchQuery .= "$field = $value AND ";
}
$searchQuery = substr($searchQuery, 0, -5);
}
// Get the objects with pagination
$sql = "SELECT * FROM $this->table $searchQuery LIMIT $limit OFFSET $offset";
$result = $db->query($sql);
$array = $db->fetch_all($result);
$sql = "SELECT COUNT(*) AS count FROM $this->table $searchQuery";
$result = $db->query($sql);
$row = $db->fetch_assoc($result);
$total = $row['count'];
$response->paginate($page, $limit, $total, $search, $filters);
return $array;
}
/**
* List objects with pagination (if set)
* @return array The list of objects in the table
*/
public function listObjectsWithPaginationIfSet(): array
{
global $response;
$page = ((int) $response->getRequestParameter('page')) ?? null; // Get the page number
$limit = ((int) $response->getRequestParameter('limit')) ?? null; // Get the number of objects per page
$search = $response->getRequestParameter('search') ?? null; // Get the search query
$filters = $response->getRequestParameter('filters') ?? null; // Get the filters ( Eg. department_id:1,role_id:2 OR department_id:1 )
// Make the filters an array
if ($filters) {
$filters = explode(',', $filters);
$temp = [];
foreach ($filters as $filter) {
$filter = explode(':', $filter);
$temp[$filter[0]] = $filter[1];
}
$filters = $temp;
}
if ($page && $limit) {
return $this->listObjectsWithPagination($page, $limit, $search, $filters);
}
return $this->listObjects();
}
/**
* Does this object exist in the database?
* @return bool True if the object exists in the database, false otherwise
*/
public function exists(): bool
{
// Check if the id is set
if (!isset($this->id)) {
return false;
}
// Check if the object exists in the database
global $db;
$id = $this->id;
$sql = "SELECT * FROM $this->table WHERE id = $id";
$result = $db->query($sql);
return $result->num_rows > 0;
}
}