| 1: | <?php declare(strict_types = 1); |
| 2: | |
| 3: | namespace PHPStan\PhpDocParser\Parser; |
| 4: | |
| 5: | use function array_reverse; |
| 6: | use function count; |
| 7: | use function implode; |
| 8: | use function intdiv; |
| 9: | use function intval; |
| 10: | use function ltrim; |
| 11: | use function str_replace; |
| 12: | use function str_split; |
| 13: | use function strlen; |
| 14: | use function strspn; |
| 15: | use function strtolower; |
| 16: | use function substr; |
| 17: | |
| 18: | class IntegerLiteralNormalizer |
| 19: | { |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | public static function normalizeToDecimal(string $literal): string |
| 26: | { |
| 27: | $literal = str_replace('_', '', $literal); |
| 28: | $sign = ''; |
| 29: | if ($literal !== '' && ($literal[0] === '-' || $literal[0] === '+')) { |
| 30: | $sign = $literal[0] === '-' ? '-' : ''; |
| 31: | $literal = substr($literal, 1); |
| 32: | } |
| 33: | |
| 34: | $prefix = strtolower(substr($literal, 0, 2)); |
| 35: | if ($prefix === '0x') { |
| 36: | $base = 16; |
| 37: | $digits = substr($literal, 2); |
| 38: | } elseif ($prefix === '0b') { |
| 39: | $base = 2; |
| 40: | $digits = substr($literal, 2); |
| 41: | } elseif ($prefix === '0o') { |
| 42: | $base = 8; |
| 43: | $digits = substr($literal, 2); |
| 44: | } elseif ($literal !== '' && $literal[0] === '0' && strspn($literal, '01234567') === strlen($literal)) { |
| 45: | $base = 8; |
| 46: | $digits = $literal; |
| 47: | } else { |
| 48: | $base = 10; |
| 49: | $digits = $literal; |
| 50: | } |
| 51: | |
| 52: | if ($base === 10) { |
| 53: | $decimal = ltrim($digits, '0'); |
| 54: | } else { |
| 55: | |
| 56: | $decimalDigits = [0]; |
| 57: | foreach (str_split($digits) as $character) { |
| 58: | $carry = intval($character, $base); |
| 59: | for ($i = 0; $i < count($decimalDigits); $i++) { |
| 60: | $product = $decimalDigits[$i] * $base + $carry; |
| 61: | $decimalDigits[$i] = $product % 10; |
| 62: | $carry = intdiv($product, 10); |
| 63: | } |
| 64: | while ($carry > 0) { |
| 65: | $decimalDigits[] = $carry % 10; |
| 66: | $carry = intdiv($carry, 10); |
| 67: | } |
| 68: | } |
| 69: | $decimal = ltrim(implode('', array_reverse($decimalDigits)), '0'); |
| 70: | } |
| 71: | |
| 72: | if ($decimal === '') { |
| 73: | return '0'; |
| 74: | } |
| 75: | |
| 76: | return $sign . $decimal; |
| 77: | } |
| 78: | |
| 79: | } |
| 80: | |