Skip to content

Instantly share code, notes, and snippets.

@Oleksandr-Moik
Last active December 17, 2024 20:57
Show Gist options
  • Save Oleksandr-Moik/2a33af34fd0064cddfc1621980b62050 to your computer and use it in GitHub Desktop.
Save Oleksandr-Moik/2a33af34fd0064cddfc1621980b62050 to your computer and use it in GitHub Desktop.
Declension helpers
<?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];
}
}
<?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