1. <?php
  2. class RequestThrottler {
  3. private $queue = []; // Queue of requests
  4. private $limit; // Maximum number of requests allowed
  5. private $timeWindow; // Time window for the limit
  6. private $lastTimestamp = 0; // Timestamp of the last request within the window
  7. public function __construct(int $limit, int $timeWindow) {
  8. $this->limit = $limit;
  9. $this->timeWindow = $timeWindow;
  10. }
  11. /**
  12. * Checks if a request is allowed based on the throttling rules.
  13. *
  14. * @return bool True if the request is allowed, false otherwise.
  15. */
  16. public function isAllowed(): bool {
  17. $currentTime = time();
  18. // Remove requests older than the time window
  19. $this->queue = array_filter($this->queue, function ($request) use ($currentTime, $this->timeWindow) {
  20. return $currentTime - $request['timestamp'] < $this->timeWindow;
  21. });
  22. // Check if the queue is full
  23. if (count($this->queue) >= $this->limit) {
  24. return false; // Throttled
  25. }
  26. $this->queue[] = ['timestamp' => $currentTime]; // Add current request to queue
  27. return true; // Allowed
  28. }
  29. /**
  30. * Processes a request.
  31. *
  32. * @param callable $callback The function to execute for the request.
  33. * @param array $data Optional data to pass to the callback.
  34. * @return mixed The result of the callback, or null on failure.
  35. * @throws Exception If the request is throttled.
  36. */
  37. public function processRequest(callable $callback, array $data = []): mixed
  38. {
  39. if (!$this->isAllowed()) {
  40. throw new Exception("Request throttled. Too many requests in a short period.");
  41. }
  42. try {
  43. return $callback($data);
  44. } catch (Exception $e) {
  45. //Handle exceptions from the callback
  46. error_log("Error processing request: " . $e->getMessage());
  47. throw $e;
  48. }
  49. }
  50. }
  51. //Example Usage
  52. /*
  53. $throttler = new RequestThrottler(5, 60); // Allow 5 requests per minute
  54. try {
  55. for ($i = 0; $i < 10; $i++) {
  56. $result = $throttler->processRequest(function ($data) use ($i) {
  57. return "Request " . $i . " processed";
  58. });
  59. echo $result . "\n";
  60. }
  61. } catch (Exception $e) {
  62. echo "Error: " . $e->getMessage() . "\n";
  63. }
  64. */
  65. ?>

Add your comment