LNumber.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. // Strip optional explicit octal prefix.
  54. if ('o' === $str[1] || 'O' === $str[1]) {
  55. $str = substr($str, 2);
  56. }
  57. // use intval instead of octdec to get proper cutting behavior with malformed numbers
  58. $attributes['kind'] = LNumber::KIND_OCT;
  59. return new LNumber(intval($str, 8), $attributes);
  60. }
  61. public function getType() : string {
  62. return 'Scalar_LNumber';
  63. }
  64. }