initial commit
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace Jakach\Logging\RuleEngine;
|
||||
|
||||
use Jakach\Logging\Model\{Rule, Alert, LogSource};
|
||||
use Jakach\Logging\Storage\Repository;
|
||||
|
||||
class Engine
|
||||
{
|
||||
private array $rateCache = [];
|
||||
private array $compiledPatterns = [];
|
||||
|
||||
public function __construct(
|
||||
private Repository $repo,
|
||||
) {}
|
||||
|
||||
public function evaluate(string $line, ?LogSource $source = null): ?Alert
|
||||
{
|
||||
$rules = $this->repo->getActiveRules();
|
||||
|
||||
foreach ($rules as $rule) {
|
||||
if ($this->matches($line, $rule)) {
|
||||
if ($rule->rateLimitSeconds !== null && !$this->repo->checkRateLimit($rule->id, $rule->rateLimitSeconds)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$message = sprintf(
|
||||
'[%s] Rule "%s" matched: %s',
|
||||
strtoupper($rule->severity->value),
|
||||
$rule->name,
|
||||
substr($line, 0, 200)
|
||||
);
|
||||
|
||||
$alert = $this->repo->createAlert(
|
||||
ruleId: $rule->id,
|
||||
ruleName: $rule->name,
|
||||
severity: $rule->severity->value,
|
||||
message: $message,
|
||||
rawLine: $line,
|
||||
sourceId: $source?->id,
|
||||
sourceName: $source?->name,
|
||||
);
|
||||
|
||||
return $alert;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function matches(string $line, Rule $rule): bool
|
||||
{
|
||||
if (!isset($this->compiledPatterns[$rule->id])) {
|
||||
$delimiter = $rule->pattern[0] ?? '/';
|
||||
$this->compiledPatterns[$rule->id] = $rule->pattern;
|
||||
}
|
||||
|
||||
return (bool) preg_match($this->compiledPatterns[$rule->id], $line);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user