1 | <?php |
||
2 | |||
3 | namespace ICanBoogie\CLDR\Supplemental\Plurals; |
||
4 | |||
5 | use function array_map; |
||
6 | use function array_walk_recursive; |
||
7 | use function explode; |
||
8 | use function ICanBoogie\iterable_every; |
||
9 | use function ICanBoogie\iterable_some; |
||
10 | |||
11 | /** |
||
12 | * Representation of plural samples. |
||
13 | * |
||
14 | * @link https://unicode.org/reports/tr35/tr35-72-numbers.html#Language_Plural_Rules |
||
15 | */ |
||
16 | final class Rule |
||
17 | { |
||
18 | public static function from(string $rule): Rule |
||
19 | { |
||
20 | return RuleCache::get( |
||
21 | $rule, |
||
22 | static fn(): Rule => new self(self::parse_rule($rule)) |
||
23 | ); |
||
24 | } |
||
25 | |||
26 | /** |
||
27 | * @return array<Relation[]> |
||
28 | * An array of 'OR' relations, where _value_ is an array of 'AND' relations. |
||
29 | */ |
||
30 | private static function parse_rule(string $rules): array |
||
31 | { |
||
32 | $relations = self::extract_relations($rules); |
||
33 | array_walk_recursive($relations, function (string &$relation): void { |
||
34 | $relation = Relation::from($relation); |
||
35 | }); |
||
36 | |||
37 | /** @var array<Relation[]> */ |
||
38 | return $relations; |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * @return array<string[]> |
||
43 | * An array of 'OR' relations, where _value_ is an array of 'AND' relations. |
||
44 | */ |
||
45 | private static function extract_relations(string $rule): array |
||
46 | { |
||
47 | return array_map( |
||
48 | static fn(string $rule): array => explode(' and ', $rule), |
||
49 | explode(' or ', $rule) |
||
50 | ); |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * @param Relation[][] $relations |
||
55 | */ |
||
56 | private function __construct( |
||
57 | private readonly array $relations |
||
58 | ) { |
||
59 | } |
||
60 | |||
61 | /** |
||
62 | * Whether a number matches the rule. |
||
63 | * |
||
64 | * @param float|int|numeric-string $number |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
![]() |
|||
65 | */ |
||
66 | public function validate(float|int|string $number): bool |
||
67 | { |
||
68 | $operands = Operands::from($number); |
||
69 | |||
70 | return $this->validate_or($operands, $this->relations); |
||
71 | } |
||
72 | |||
73 | /** |
||
74 | * @param Relation[][] $or_relations |
||
75 | */ |
||
76 | public function validate_or(Operands $operands, iterable $or_relations): bool |
||
77 | { |
||
78 | return iterable_some( |
||
79 | $or_relations, |
||
80 | fn($and_relations) => $this->validate_and($operands, $and_relations) |
||
81 | ); |
||
82 | } |
||
83 | |||
84 | /** |
||
85 | * @param Relation[] $and_relations |
||
86 | */ |
||
87 | public function validate_and(Operands $operands, iterable $and_relations): bool |
||
88 | { |
||
89 | return iterable_every( |
||
90 | $and_relations, |
||
91 | fn(Relation $relation) => $relation->evaluate($operands) |
||
92 | ); |
||
93 | } |
||
94 | } |
||
95 |