Skip to content

Commit 15c3cf2

Browse files
committed
Use a regex to check if an ID contains a word from the blocklist
1 parent 6df4c12 commit 15c3cf2

File tree

1 file changed

+8
-21
lines changed

1 file changed

+8
-21
lines changed

src/Sqids.php

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -592,11 +592,13 @@ class Sqids implements SqidsInterface
592592

593593
protected MathInterface $math;
594594

595+
protected ?string $blocklist = null;
596+
595597
/** @throws \InvalidArgumentException */
596598
public function __construct(
597599
protected string $alphabet = self::DEFAULT_ALPHABET,
598600
protected int $minLength = self::DEFAULT_MIN_LENGTH,
599-
protected array $blocklist = self::DEFAULT_BLOCKLIST,
601+
array $blocklist = self::DEFAULT_BLOCKLIST,
600602
) {
601603
$this->math = $this->getMathExtension();
602604

@@ -628,9 +630,12 @@ public function __construct(
628630
$alphabetPattern = '/^[' . preg_quote($alphabet, '/') . ']+$/i';
629631
foreach ($blocklist as $word) {
630632
if (strlen((string) $word) >= 3 && preg_match($alphabetPattern, $word)) {
631-
$filteredBlocklist[] = strtolower((string) $word);
633+
$filteredBlocklist[] = preg_quote((string) $word, '/');
632634
}
633635
}
636+
if ($filteredBlocklist) {
637+
$this->blocklist = '/(' . implode('|', $filteredBlocklist) . ')/i';
638+
}
634639

635640
$this->alphabet = $this->shuffle($alphabet);
636641
$this->blocklist = $filteredBlocklist;
@@ -799,25 +804,7 @@ protected function toNumber(string $id, string $alphabet): int
799804

800805
protected function isBlockedId(string $id): bool
801806
{
802-
$id = strtolower($id);
803-
804-
foreach ($this->blocklist as $word) {
805-
if (strlen((string) $word) <= strlen($id)) {
806-
if (strlen($id) <= 3 || strlen((string) $word) <= 3) {
807-
if ($id == $word) {
808-
return true;
809-
}
810-
} elseif (preg_match('/~[0-9]+~/', (string) $word)) {
811-
if (str_starts_with($id, (string) $word) || strrpos($id, (string) $word) === strlen($id) - strlen((string) $word)) {
812-
return true;
813-
}
814-
} elseif (str_contains($id, (string) $word)) {
815-
return true;
816-
}
817-
}
818-
}
819-
820-
return false;
807+
return $this->blocklist !== null && preg_match($this->blocklist, $id);
821808
}
822809

823810
protected static function maxValue(): int

0 commit comments

Comments
 (0)