diff --git a/app/app/Support/RubricKey.php b/app/app/Support/RubricKey.php new file mode 100644 index 00000000..d8f5f893 --- /dev/null +++ b/app/app/Support/RubricKey.php @@ -0,0 +1,38 @@ + 'а', 'c' => 'с', 'e' => 'е', 'o' => 'о', 'p' => 'р', 'x' => 'х', + 'y' => 'у', 'k' => 'к', 'm' => 'м', 'h' => 'н', 't' => 'т', 'b' => 'в', + ]; + + public static function make(?string $raw): string + { + $s = mb_strtolower(trim((string) $raw), 'UTF-8'); + + if (preg_match('/\p{Cyrillic}/u', $s) === 1) { + $s = strtr($s, self::LOOKALIKES); + } + + $s = str_replace('ё', 'е', $s); + $s = (string) preg_replace('/[^\p{L}\p{N}]+/u', ' ', $s); + + return trim((string) preg_replace('/\s+/u', ' ', $s)); + } +} diff --git a/app/tests/Unit/Support/RubricKeyTest.php b/app/tests/Unit/Support/RubricKeyTest.php new file mode 100644 index 00000000..047e2816 --- /dev/null +++ b/app/tests/Unit/Support/RubricKeyTest.php @@ -0,0 +1,30 @@ +toBe(RubricKey::make(' окна ')) + ->and(RubricKey::make('Окна'))->toBe(RubricKey::make('«Окна».')) + ->and(RubricKey::make('Ремонт, стройка'))->toBe(RubricKey::make('ремонт стройка')); +}); + +test('ё и е — одна буква', function () { + expect(RubricKey::make('Клёны'))->toBe(RubricKey::make('Клены')); +}); + +test('латинские двойники в русском слове приводятся к кириллице', function () { + // «Окнa» — последняя буква латинская. + expect(RubricKey::make("Окн\u{0061}"))->toBe(RubricKey::make('Окна')); +}); + +test('чисто латинское название не калечится', function () { + expect(RubricKey::make('SPA'))->toBe('spa') + ->and(RubricKey::make('IT'))->toBe('it'); +}); + +test('пустая строка даёт пустой ключ', function () { + expect(RubricKey::make(null))->toBe('') + ->and(RubricKey::make(' '))->toBe(''); +});