1. <?php
  2. class JsonPatternMatcher {
  3. private $patterns = [];
  4. private $rateLimit = 10; // Max requests per minute
  5. private $requestTimestamps = [];
  6. public function __construct(array $patterns) {
  7. $this->patterns = $patterns;
  8. }
  9. public function match(string $jsonPayload): ?string {
  10. // Check Rate Limit
  11. $now = time();
  12. if (isset($this->requestTimestamps[$this->getTimestamp($jsonPayload)]) &&
  13. $now - $this->requestTimestamps[$this->getTimestamp($jsonPayload)] < 60) {
  14. return 'Rate limit exceeded.';
  15. }
  16. $this->requestTimestamps[$this->getTimestamp($jsonPayload)] = $now;
  17. foreach ($this->patterns as $pattern => $regex) {
  18. if (preg_match($regex, $jsonPayload)) {
  19. return $pattern; // Return the matching pattern
  20. }
  21. }
  22. return null; // No pattern matched
  23. }
  24. private function getTimestamp(string $jsonPayload): int {
  25. // Use a hash of the JSON payload as a timestamp
  26. return hash('sha256', $jsonPayload);
  27. }
  28. }
  29. // Example Usage
  30. $patterns = [
  31. 'user_creation' => '/{"action": "user_creation", "username": "[a-zA-Z0-9]+"/i',
  32. 'product_update' => '/{"action": "product_update", "product_id": \\d+}/i',
  33. 'order_placement' => '/{"action": "order_placement", "order_id": \\d+}/i'
  34. ];
  35. $matcher = new JsonPatternMatcher($patterns);
  36. //Test cases
  37. $json1 = '{"action": "user_creation", "username": "john_doe"}';
  38. $json2 = '{"action": "product_update", "product_id": 123}';
  39. $json3 = '{"action": "order_placement", "order_id": 456}';
  40. $json4 = '{"action": "unknown"}';
  41. $json5 = '{"action": "user_creation", "username": "jane123"}'; //same as json1
  42. echo "Testing JSON1: " . $matcher->match($json1) . "\n";
  43. echo "Testing JSON2: " . $matcher->match($json2) . "\n";
  44. echo "Testing JSON3: " . $matcher->match($json3) . "\n";
  45. echo "Testing JSON4: " . $matcher->match($json4) . "\n";
  46. echo "Testing JSON5: " . $matcher->match($json5) . "\n";
  47. //Simulate rate limiting
  48. for ($i = 0; $i < 12; $i++) {
  49. echo "Testing JSON1 (rate limited): " . $matcher->match($json1) . "\n";
  50. }
  51. ?>

Add your comment