Files
api/services/nginx/app/objects/ratelimit_o.php
T
2025-01-29 14:27:44 +01:00

111 lines
3.0 KiB
PHP

<?php
namespace objects;
use classes\db;
use classes\object_property;
use traits\db_object_t;
class ratelimit_o extends db
{
use db_object_t;
public object_property $ip;
public object_property $count;
public object_property $total_count;
public function structure(): void
{
$this->setTable('ratelimit');
}
public function getObjectProperties(): void
{
$this->ip = new object_property($this->table, $this->id, 'ip', 'string', true);
$this->count = new object_property($this->table, $this->id, 'count', 'int', true);
$this->total_count = new object_property($this->table, $this->id, 'total_count', 'int', true);
}
public function getRateLimitByIp(string $ip): ratelimit_o
{
global $db;
// Get the record from the database
$sql = "SELECT * FROM $this->table WHERE ip = '$ip'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$this->id = $result->fetch_assoc()['id'];
$this->getObjectProperties();
}
return $this;
}
public function getRateLimitById(int $id): ratelimit_o
{
global $db;
// Get the record from the database
$sql = "SELECT * FROM $this->table WHERE id = $id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
$this->id = $id;
$this->getObjectProperties();
}
return $this;
}
public function increment(int $id, int $count): void
{
global $db;
$this->id = $id;
// Update the record in the database
$sql = "UPDATE $this->table SET count = count + $count, total_count = total_count + $count WHERE id = $this->id";
$db->query($sql);
// Set the values of the object properties
$this->getObjectProperties();
}
public function reset(int $id): void
{
global $db;
$this->id = $id;
// Update the record in the database
$sql = "UPDATE $this->table SET count = 0 WHERE id = $this->id";
$db->query($sql);
// Set the values of the object properties
$this->getObjectProperties();
}
public function create(string $ip): void
{
global $db;
// Avoid SQL injection
$ip = $db->escape_string($ip);
// Create a new record in the database
$sql = "INSERT INTO $this->table (ip, count, total_count) VALUES ('$ip', 1, 1)";
$db->query($sql);
// Get the id of the new record
$this->id = $db->insert_id();
// Set the values of the object properties
$this->getObjectProperties();
}
public function getOrCreateRateLimitByIp(string $ip): ratelimit_o
{
$ratelimit = $this->getRateLimitByIp($ip);
if (!$ratelimit->id) {
$this->create($ip);
return $this;
}
return $ratelimit;
}
public function resetAll(): void
{
global $db;
// Reset all the ratelimits
$sql = "UPDATE $this->table SET count = 0";
$db->query($sql);
}
}