MediaWiki master
Plural.php
Go to the documentation of this file.
1<?php
8
10
27class Plural {
28
32 public function __construct(
33 private readonly Provider $provider,
34 ) {
35 }
36
50 public function process( float $count, array $forms ): string {
51 // For "explicit" forms such as "0=No items", "1=One item", or "other=Items"
52 // we’ll store them in an associative array if we parse them that way.
53 $explicitForms = [];
54
55 // For "default" (non-explicit) forms such as [ 'item', 'items' ],
56 // we store them in a sequential array with integer keys.
57 $defaultForms = [];
58
59 // Separate explicit forms ("n=text") from default forms
60 foreach ( $forms as $form ) {
61 if ( str_contains( $form, '=' ) ) {
62 [
63 $key,
64 $text,
65 ] = explode( '=', $form, 2 );
66 // If key is purely numeric AND matches $count, return immediately:
67 if ( is_numeric( $key ) && (float)$key === $count ) {
68 return $text;
69 }
70 // Otherwise, treat it as an explicit string key
71 $explicitForms[$key] = $text;
72 } else {
73 // Default form
74 $defaultForms[] = $form;
75 }
76 }
77
78 // Figure out the plural category: "one", "few", "other", etc.
79 $pluralType = $this->provider->getPluralProvider()->getPluralRuleType( $count );
80
81 // If we have an explicit form matching $pluralType` as a key, use it:
82 // e.g., "one" => "Item", "other" => "Items"
83 if ( array_key_exists( $pluralType, $explicitForms ) ) {
84 return $explicitForms[$pluralType];
85 }
86
87 // Otherwise, fallback to the default forms (sequential)
88 // If we find a default that exactly matches $pluralType as a string, use that:
89 $foundKey = array_search( $pluralType, $defaultForms, true );
90 if ( $foundKey !== false ) {
91 return $defaultForms[$foundKey];
92 }
93
94 // Else, use the numeric index from the language’s plural rules
95 // (e.g. 0 => singular form, 1 => plural form, etc.)
96 if ( count( $defaultForms ) > 0 ) {
97 $index = $this->provider->getPluralProvider()->getPluralRuleIndexNumber( $count );
98 // Guard in case $index is out of range
99 $index = min( $index, count( $defaultForms ) - 1 );
100
101 return $defaultForms[$index];
102 }
103
104 // If no forms were provided at all, just return an empty string
105 return '';
106 }
107}
__construct(private readonly Provider $provider,)
Definition Plural.php:32
process(float $count, array $forms)
Selects and returns the pluralized text form based on a numeric count.
Definition Plural.php:50