1. <?php
  2. class RecordHasher {
  3. private $hash_table = [];
  4. private $rate_limit = 10; // Requests per second
  5. private $rate_limit_window = 1; // Seconds
  6. public function __construct($rate_limit = 10, $rate_limit_window = 1) {
  7. $this->rate_limit = $rate_limit;
  8. $this->rate_limit_window = $rate_limit_window;
  9. }
  10. /**
  11. * Hashes a record value and checks rate limit.
  12. *
  13. * @param string $record_value The record value to hash.
  14. * @return string|false The hashed value on success, false on rate limit exceeded.
  15. */
  16. public function hashRecord(string $record_value): string|false {
  17. $timestamp = time();
  18. // Clean up old requests
  19. $this->cleanupRateLimit($timestamp);
  20. // Check rate limit
  21. if ($this->isRateLimited()) {
  22. return false; // Rate limit exceeded
  23. }
  24. // Hash the record value
  25. $hash = hash('sha256', $record_value);
  26. // Store the hash and timestamp
  27. $this->storeHash($record_value, $hash, $timestamp);
  28. return $hash;
  29. }
  30. /**
  31. * Checks if the rate limit has been exceeded.
  32. *
  33. * @return bool True if rate limited, false otherwise.
  34. */
  35. private function isRateLimited(): bool {
  36. $now = time();
  37. $requests = array_count_values(array_filter($this->hash_table, function ($item) use ($now) => $now - $item['timestamp'] < $this->rate_limit_window));
  38. if (isset($requests[$now])) {
  39. if ($requests[$now] >= $this->rate_limit) {
  40. return true;
  41. }
  42. }
  43. return false;
  44. }
  45. /**
  46. * Cleans up old requests from the hash table.
  47. *
  48. * @param int $timestamp The current timestamp.
  49. */
  50. private function cleanupRateLimit(int $timestamp): void {
  51. $this->hash_table = array_filter($this->hash_table, function ($item) use ($timestamp) {
  52. return $timestamp - $item['timestamp'] < $this->rate_limit_window;
  53. });
  54. }
  55. /**
  56. * Stores the hash and timestamp.
  57. *
  58. * @param string $record_value The record value.
  59. * @param string $hash The hashed value.
  60. * @param int $timestamp The timestamp.
  61. */
  62. private function storeHash(string $record_value, string $hash, int $timestamp): void {
  63. $this->hash_table[] = ['record_value' => $record_value, 'hash' => $hash, 'timestamp' => $timestamp];
  64. }
  65. }
  66. ?>

Add your comment