Back to Text class

Method plural

public static string
plural
(mixed $string, mixed $n)
Like Text::sprintf but tries to pluralise the string.
Parameters
  • string $string The format string.
  • int $n The number of items
Returns
  • string The translated strings or the key if 'script' is true in the array of options
Since
  • 1.7.0
Class: Text
Project: Joomla

Method plural - Source code

/**
 * Like Text::sprintf but tries to pluralise the string.
 *
 * Note that this method can take a mixed number of arguments as for the sprintf function.
 *
 * The last argument can take an array of options:
 *
 * array('jsSafe'=>boolean, 'interpretBackSlashes'=>boolean, 'script'=>boolean)
 *
 * where:
 *
 * jsSafe is a boolean to generate a javascript safe strings.
 * interpretBackSlashes is a boolean to interpret backslashes \\->\, \n->new line, \t->tabulation.
 * script is a boolean to indicate that the string will be push in the javascript language store.
 *
 * Examples:
 * `<script>alert(Joomla.Text._('<?php echo Text::plural("COM_PLUGINS_N_ITEMS_UNPUBLISHED", 1, array("script"=>true)); ?>'));</script>`
 * will generate an alert message containing '1 plugin successfully disabled'
 * `<?php echo Text::plural('COM_PLUGINS_N_ITEMS_UNPUBLISHED', 1); ?>` will generate a '1 plugin successfully disabled' string
 *
 * @param   string   $string  The format string.
 * @param   integer  $n       The number of items
 *
 * @return  string  The translated strings or the key if 'script' is true in the array of options
 *
 * @since   1.7.0
 */
public static function plural($string, $n)
{
    $lang = Factory::getLanguage();
    $args = \func_get_args();
    $count = \count($args);
    // Try the key from the language plural potential suffixes
    $found = false;
    $suffixes = $lang->getPluralSuffixes((int) $n);
    // Add the count as possible suffix to allow for eg "a dozen" with suffix _12.
    // Only do that if it is a real plural (more than one) to avoid issues with languages. See https://github.com/joomla/joomla-cms/pull/29029
    if ($n != 1) {
        array_unshift($suffixes, (int) $n);
    }
    foreach ($suffixes as $suffix) {
        $key = $string . '_' . $suffix;
        if ($lang->hasKey($key)) {
            $found = true;
            break;
        }
    }
    if (!$found) {
        // Not found so revert to the original.
        $key = $string;
    }
    if (\is_array($args[$count - 1])) {
        $args[0] = $lang->_($key, \array_key_exists('jsSafe', $args[$count - 1]) ? $args[$count - 1]['jsSafe'] : false, \array_key_exists('interpretBackSlashes', $args[$count - 1]) ? $args[$count - 1]['interpretBackSlashes'] : true);
        if (\array_key_exists('script', $args[$count - 1]) && $args[$count - 1]['script']) {
            static::$strings[$key] = \call_user_func_array('sprintf', $args);
            return $key;
        }
    } else {
        $args[0] = $lang->_($key);
    }
    return \call_user_func_array('sprintf', $args);
}