Merge branch '5.2' into 5.3
[GitHub/WoltLab/WCF.git] / wcfsetup / install / files / lib / system / template / plugin / PluralFunctionTemplatePlugin.class.php
1 <?php
2 namespace wcf\system\template\plugin;
3 use wcf\system\exception\SystemException;
4 use wcf\system\language\I18nPlural;
5 use wcf\system\template\TemplateEngine;
6 use wcf\util\StringUtil;
7
8 /**
9 * Template function plugin which generate plural phrases.
10 *
11 * Languages vary in how they handle plurals of nouns or unit expressions.
12 * Some languages have two forms, like English; some languages have only a
13 * single form; and some languages have multiple forms.
14 *
15 * Supported parameters:
16 * value (number|array|Countable - required)
17 * other (string - required)
18 * zero (string), one (string), two (string), few (string), many (string)
19 *
20 * Usage:
21 * {plural value=$number zero='0' one='1' two='2' few='few' many='many' other='#'}
22 * There {plural value=$worlds one='is one world' other='are # worlds'}
23 * Updated {plural value=$minutes 0='just now' 1='one minute ago' other='# minutes ago'}
24 *
25 * @author Marcel Werk
26 * @copyright 2001-2020 WoltLab GmbH
27 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
28 * @package WoltLabSuite\Core\System\Template\Plugin
29 * @since 5.3
30 */
31 class PluralFunctionTemplatePlugin implements IFunctionTemplatePlugin {
32 /**
33 * @inheritDoc
34 */
35 public function execute($tagArgs, TemplateEngine $tplObj) {
36 if (!isset($tagArgs['value'])) {
37 throw new SystemException("Missing attribute 'value'");
38 }
39 if (!isset($tagArgs['other'])) {
40 throw new SystemException("Missing attribute 'other'");
41 }
42
43 $value = $tagArgs['value'];
44 if (is_countable($value)) {
45 $value = count($value);
46 }
47
48 // handle numeric attributes
49 foreach ($tagArgs as $key => $_value) {
50 if (is_numeric($key)) {
51 if ($key == $value) return $_value;
52 }
53 }
54
55 $category = I18nPlural::getCategory($value);
56 if (!isset($tagArgs[$category])) {
57 $category = I18nPlural::PLURAL_OTHER;
58 }
59
60 $string = $tagArgs[$category];
61 if (strpos($string, '#') !== false) {
62 return str_replace('#', StringUtil::formatNumeric($value), $string);
63 }
64
65 return $string;
66 }
67 }