41 lines
1.1 KiB
PHP
41 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Domain\Rule\MatchMode;
|
|
|
|
final class ContentMatcher
|
|
{
|
|
public static function match(string $input, string $pattern, MatchMode $mode): bool
|
|
{
|
|
if (blank($input) || blank($pattern)) {
|
|
return false;
|
|
}
|
|
|
|
return match ($mode) {
|
|
MatchMode::Exact => strcasecmp($input, $pattern) === 0,
|
|
MatchMode::Contains => str_contains($input, $pattern) ,
|
|
MatchMode::StartsWith => str_starts_with($input, $pattern),
|
|
MatchMode::EndsWith => str_ends_with($input, $pattern),
|
|
MatchMode::InList => self::matchList($input, $pattern),
|
|
MatchMode::Regex => preg_match($pattern, $input) === 1,
|
|
};
|
|
}
|
|
|
|
private static function matchList(string $input, string $pattern): bool
|
|
{
|
|
$patterns = collect(explode(',', $pattern))
|
|
->map(fn ($s) => trim($s))
|
|
->filter(fn ($s) => filled($s))
|
|
->toArray();
|
|
|
|
foreach ($patterns as $search) {
|
|
if (self::match($input, $search, MatchMode::Exact)) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|