Last active
December 17, 2024 20:57
-
-
Save Oleksandr-Moik/2a33af34fd0064cddfc1621980b62050 to your computer and use it in GitHub Desktop.
Declension helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if (!function_exists('declension_key')) { | |
/** Translation based declension function */ | |
function declension_key(int $number, string $key, ?string $locale = null): string | |
{ | |
$locale = $locale ?: app()->getLocale(); | |
$words = trans('declensions.' . $key, [], $locale); | |
if (is_string($words)) { | |
$words = explode('|', $words); | |
} | |
return declension_word($number, $words); | |
} | |
} | |
if (!function_exists('declension_word')) { | |
/** | |
* <p>приклад 0 1 2 </p> | |
* <p>declension_word(21, ['елемент', 'елемента', 'елементів']) = елемент</p> | |
* <p>declension_word(24, ['елемент', 'елемента', 'елементів']) = елементи</p> | |
* <p>declension_word(36, ['елемент', 'елемента', 'елементів']) = елементів</p> | |
* | |
* @param int $number число, від якого залежатиме форма потрібного слова; | |
* @param list<string> $words масив слова, що схиляється в трьох варіантах (1, 2, багато) | |
*/ | |
function declension_word(int $number, array $words): string | |
{ | |
$indexes = [2, 0, 1, 1, 1, 2]; // індекси в масив слів | |
$index = (4 < ($number % 100) && ($number % 100) < 20) | |
? 2 // 5 - 19 | |
: $indexes[min($number % 10, 5)]; // *1 - *5 | |
return $words[$index]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// example of lang/uk/declensions.php | |
return [ | |
'element' => ['елемент', 'елемента', 'елементів'], | |
'minute' => ['хвилина', 'хвилини', 'хвилин'], | |
'score' => ['бал', 'бали', 'балів'], | |
'question' => ['питання', 'питання', 'питань'], | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment