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
<?php
namespace ICanBoogie\CLDR;
class NumberPatternParser
{
const PATTERN_REGEX = '/^(.*?)[#,\.0]+(.*?)$/';
static private $initial_format = [
'positive_prefix' => '',
'positive_suffix' => '',
'negative_prefix' => '',
'negative_suffix' => '',
'multiplier' => 1,
'decimal_digits' => 0,
'max_decimal_digits' => 0,
'integer_digits' => 0,
'group_size1' => 0,
'group_size2' => 0
];
static public function parse($pattern)
{
$format = self::$initial_format;
self::parse_multiple_patterns($pattern, $format);
self::parse_multiplier($pattern, $format);
self::parse_decimal_part($pattern, $format);
self::parse_integer_part($pattern, $format);
self::parse_group_sizes($pattern, $format);
return $format;
}
static private function parse_multiple_patterns(&$pattern, array &$format)
{
$patterns = explode(';', $pattern);
if (preg_match(self::PATTERN_REGEX, $patterns[0], $matches))
{
$format['positive_prefix'] = $matches[1];
$format['positive_suffix'] = $matches[2];
}
if (isset($patterns[1]) && preg_match(self::PATTERN_REGEX, $patterns[1], $matches))
{
$format['negative_prefix'] = $matches[1];
$format['negative_suffix'] = $matches[2];
}
else
{
$format['negative_prefix'] = '-' . $format['positive_prefix'];
$format['negative_suffix'] = $format['positive_suffix'];
}
$pattern = $patterns[0];
}
static private function parse_multiplier(&$pattern, array &$format)
{
if (strpos($pattern, '%') !== false)
{
$format['multiplier'] = 100;
}
else
{
if (strpos($pattern, '‰') !== false)
{
$format['multiplier'] = 1000;
}
}
}
static private function parse_decimal_part(&$pattern, array &$format)
{
$pos = strpos($pattern, '.');
if ($pos !== false)
{
$pos2 = strrpos($pattern, '0');
$format['decimal_digits'] = $pos2 > $pos
? $pos2 - $pos
: 0;
$pos3 = strrpos($pattern, '#');
$format['max_decimal_digits'] = $pos3 >= $pos2
? $pos3 - $pos
: $format['decimal_digits'];
$pattern = substr($pattern, 0, $pos);
}
}
static private function parse_integer_part(&$pattern, array &$format)
{
$p = str_replace(',', '', $pattern);
$pos = strpos($p, '0');
$format['integer_digits'] = $pos !== false
? strrpos($p, '0') - $pos + 1
: 0;
}
static private function parse_group_sizes(&$pattern, array &$format)
{
$p = str_replace('#', '0', $pattern);
$pos = strrpos($pattern, ',');
if ($pos !== false)
{
$pos2 = strrpos(substr($p, 0, $pos), ',');
$format['group_size1'] = strrpos($p, '0') - $pos;
$format['group_size2'] = $pos2 !== false ? $pos - $pos2 - 1 : 0;
}
}
}