1. <?php
  2. /**
  3. * Initializes CLI argument components with rate limiting.
  4. *
  5. * @param array $argv The command-line arguments array.
  6. * @param array $rateLimits An associative array defining rate limits for each component.
  7. * Example: ['component1' => ['limit' => 10, 'period' => 60], ...]
  8. * @return array An array containing the initialized components and any errors.
  9. */
  10. function initializeCLIArgsWithRateLimiting(array $argv, array $rateLimits): array
  11. {
  12. $components = [];
  13. $errors = [];
  14. foreach ($rateLimits as $component => $limitInfo) {
  15. $limit = $limitInfo['limit'];
  16. $period = $limitInfo['period'];
  17. // Initialize the component
  18. $components[$component] = [];
  19. // Initialize a counter for the component
  20. $components[$component]['count'] = 0;
  21. $components[$component]['last_reset'] = time();
  22. // Check if the component exceeds the rate limit
  23. if ($components[$component]['count'] >= $limit) {
  24. $errors[] = "Rate limit exceeded for component: " . $component . " (limit: " . $limit . " per " . $period . " seconds)";
  25. // Optionally, you could implement a queue or delay mechanism here
  26. // to handle exceeding the rate limit.
  27. }
  28. // Increment the component counter
  29. $components[$component]['count']++;
  30. }
  31. return ['components' => $components, 'errors' => $errors];
  32. }
  33. // Example Usage (uncomment to test)
  34. /*
  35. $argv = ['--component1', '--component2', '--component1', '--component1', '--component3'];
  36. $rateLimits = [
  37. 'component1' => ['limit' => 2, 'period' => 30],
  38. 'component2' => ['limit' => 1, 'period' => 60],
  39. 'component3' => ['limit' => 3, 'period' => 120],
  40. ];
  41. $result = initializeCLIArgsWithRateLimiting($argv, $rateLimits);
  42. print_r($result);
  43. */
  44. ?>

Add your comment