<?php
class RecordHasher {
private $hash_table = [];
private $rate_limit = 10; // Requests per second
private $rate_limit_window = 1; // Seconds
public function __construct($rate_limit = 10, $rate_limit_window = 1) {
$this->rate_limit = $rate_limit;
$this->rate_limit_window = $rate_limit_window;
}
/**
* Hashes a record value and checks rate limit.
*
* @param string $record_value The record value to hash.
* @return string|false The hashed value on success, false on rate limit exceeded.
*/
public function hashRecord(string $record_value): string|false {
$timestamp = time();
// Clean up old requests
$this->cleanupRateLimit($timestamp);
// Check rate limit
if ($this->isRateLimited()) {
return false; // Rate limit exceeded
}
// Hash the record value
$hash = hash('sha256', $record_value);
// Store the hash and timestamp
$this->storeHash($record_value, $hash, $timestamp);
return $hash;
}
/**
* Checks if the rate limit has been exceeded.
*
* @return bool True if rate limited, false otherwise.
*/
private function isRateLimited(): bool {
$now = time();
$requests = array_count_values(array_filter($this->hash_table, function ($item) use ($now) => $now - $item['timestamp'] < $this->rate_limit_window));
if (isset($requests[$now])) {
if ($requests[$now] >= $this->rate_limit) {
return true;
}
}
return false;
}
/**
* Cleans up old requests from the hash table.
*
* @param int $timestamp The current timestamp.
*/
private function cleanupRateLimit(int $timestamp): void {
$this->hash_table = array_filter($this->hash_table, function ($item) use ($timestamp) {
return $timestamp - $item['timestamp'] < $this->rate_limit_window;
});
}
/**
* Stores the hash and timestamp.
*
* @param string $record_value The record value.
* @param string $hash The hashed value.
* @param int $timestamp The timestamp.
*/
private function storeHash(string $record_value, string $hash, int $timestamp): void {
$this->hash_table[] = ['record_value' => $record_value, 'hash' => $hash, 'timestamp' => $timestamp];
}
}
?>
Add your comment