1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
<?php
namespace ICanBoogie\CLDR\Plurals;
use ICanBoogie\CLDR\Number;
final class Samples implements \IteratorAggregate
{
const INFINITY = '…';
const SAMPLE_RANGE_SEPARATOR = '~';
const TYPE_INTEGER = 'integer';
const TYPE_DECIMAL = 'decimal';
static private $instances = [];
static public function from($samples_string)
{
$instance = &self::$instances[$samples_string];
return $instance ?: $instance = new static(self::parse_rules($samples_string));
}
static private function parse_rules($sample_string)
{
$samples = [];
$type_and_samples_string_list = array_slice(explode('@', $sample_string), 1);
foreach ($type_and_samples_string_list as $type_and_samples_string)
{
list($type, $samples_string) = explode(' ', trim($type_and_samples_string), 2);
$samples[$type] = self::parse_samples($type, $samples_string);
}
return call_user_func_array('array_merge', $samples);
}
static private function parse_samples($type, $samples_string)
{
$samples = [];
foreach (explode(', ', $samples_string) as $sample)
{
if ($sample === self::INFINITY)
{
continue;
}
if (strpos($sample, self::SAMPLE_RANGE_SEPARATOR) === false)
{
$samples[] = self::cast($type, $sample);
continue;
}
list($start, $end) = explode(self::SAMPLE_RANGE_SEPARATOR, $sample);
$samples[] = [ self::cast($type, $start), self::cast($type, $end) ];
}
return $samples;
}
static private function cast($type, $number)
{
return $type === self::TYPE_DECIMAL ? (float) $number : (int) $number;
}
static private function precision_from($number)
{
return Number::precision_from($number);
}
private $samples;
private function __construct(array $samples)
{
$this->samples = $samples;
}
public function getIterator()
{
foreach ($this->samples as $sample)
{
if (!is_array($sample))
{
yield $sample;
continue;
}
list($start, $end) = $sample;
$precision = self::precision_from($start) ?: self::precision_from($end);
$step = 1 / (int) ('1' . str_repeat('0', $precision));
$times = ($end - $start) / $step;
for ($i = 0 ; $i < $times + 1 ; $i++)
{
yield (string) ($start + $step * $i);
}
}
}
}