<?php
class JsonPatternMatcher {
private $patterns = [];
private $rateLimit = 10; // Max requests per minute
private $requestTimestamps = [];
public function __construct(array $patterns) {
$this->patterns = $patterns;
}
public function match(string $jsonPayload): ?string {
// Check Rate Limit
$now = time();
if (isset($this->requestTimestamps[$this->getTimestamp($jsonPayload)]) &&
$now - $this->requestTimestamps[$this->getTimestamp($jsonPayload)] < 60) {
return 'Rate limit exceeded.';
}
$this->requestTimestamps[$this->getTimestamp($jsonPayload)] = $now;
foreach ($this->patterns as $pattern => $regex) {
if (preg_match($regex, $jsonPayload)) {
return $pattern; // Return the matching pattern
}
}
return null; // No pattern matched
}
private function getTimestamp(string $jsonPayload): int {
// Use a hash of the JSON payload as a timestamp
return hash('sha256', $jsonPayload);
}
}
// Example Usage
$patterns = [
'user_creation' => '/{"action": "user_creation", "username": "[a-zA-Z0-9]+"/i',
'product_update' => '/{"action": "product_update", "product_id": \\d+}/i',
'order_placement' => '/{"action": "order_placement", "order_id": \\d+}/i'
];
$matcher = new JsonPatternMatcher($patterns);
//Test cases
$json1 = '{"action": "user_creation", "username": "john_doe"}';
$json2 = '{"action": "product_update", "product_id": 123}';
$json3 = '{"action": "order_placement", "order_id": 456}';
$json4 = '{"action": "unknown"}';
$json5 = '{"action": "user_creation", "username": "jane123"}'; //same as json1
echo "Testing JSON1: " . $matcher->match($json1) . "\n";
echo "Testing JSON2: " . $matcher->match($json2) . "\n";
echo "Testing JSON3: " . $matcher->match($json3) . "\n";
echo "Testing JSON4: " . $matcher->match($json4) . "\n";
echo "Testing JSON5: " . $matcher->match($json5) . "\n";
//Simulate rate limiting
for ($i = 0; $i < 12; $i++) {
echo "Testing JSON1 (rate limited): " . $matcher->match($json1) . "\n";
}
?>
Add your comment