LNumber.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Scalar;
  3. use PhpParser\Error;
  4. use PhpParser\Node\Scalar;
  5. class LNumber extends Scalar
  6. {
  7. /* For use in "kind" attribute */
  8. const KIND_BIN = 2;
  9. const KIND_OCT = 8;
  10. const KIND_DEC = 10;
  11. const KIND_HEX = 16;
  12. /** @var int Number value */
  13. public $value;
  14. /**
  15. * Constructs an integer number scalar node.
  16. *
  17. * @param int $value Value of the number
  18. * @param array $attributes Additional attributes
  19. */
  20. public function __construct(int $value, array $attributes = []) {
  21. $this->attributes = $attributes;
  22. $this->value = $value;
  23. }
  24. public function getSubNodeNames() : array {
  25. return ['value'];
  26. }
  27. /**
  28. * Constructs an LNumber node from a string number literal.
  29. *
  30. * @param string $str String number literal (decimal, octal, hex or binary)
  31. * @param array $attributes Additional attributes
  32. * @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5)
  33. *
  34. * @return LNumber The constructed LNumber, including kind attribute
  35. */
  36. public static function fromString(string $str, array $attributes = [], bool $allowInvalidOctal = false) : LNumber {
  37. $str = str_replace('_', '', $str);
  38. if ('0' !== $str[0] || '0' === $str) {
  39. $attributes['kind'] = LNumber::KIND_DEC;
  40. return new LNumber((int) $str, $attributes);
  41. }
  42. if ('x' === $str[1] || 'X' === $str[1]) {
  43. $attributes['kind'] = LNumber::KIND_HEX;
  44. return new LNumber(hexdec($str), $attributes);
  45. }
  46. if ('b' === $str[1] || 'B' === $str[1]) {
  47. $attributes['kind'] = LNumber::KIND_BIN;
  48. return new LNumber(bindec($str), $attributes);
  49. }
  50. if (!$allowInvalidOctal && strpbrk($str, '89')) {
  51. throw new Error('Invalid numeric literal', $attributes);
  52. }
  53. // use intval instead of octdec to get proper cutting behavior with malformed numbers
  54. $attributes['kind'] = LNumber::KIND_OCT;
  55. return new LNumber(intval($str, 8), $attributes);
  56. }
  57. public function getType() : string {
  58. return 'Scalar_LNumber';
  59. }
  60. }