Int_.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Scalar;
  3. use PhpParser\Error;
  4. use PhpParser\Node\Scalar;
  5. class Int_ extends Scalar {
  6. /* For use in "kind" attribute */
  7. public const KIND_BIN = 2;
  8. public const KIND_OCT = 8;
  9. public const KIND_DEC = 10;
  10. public const KIND_HEX = 16;
  11. /** @var int Number value */
  12. public int $value;
  13. /**
  14. * Constructs an integer number scalar node.
  15. *
  16. * @param int $value Value of the number
  17. * @param array<string, mixed> $attributes Additional attributes
  18. */
  19. public function __construct(int $value, array $attributes = []) {
  20. $this->attributes = $attributes;
  21. $this->value = $value;
  22. }
  23. public function getSubNodeNames(): array {
  24. return ['value'];
  25. }
  26. /**
  27. * Constructs an Int node from a string number literal.
  28. *
  29. * @param string $str String number literal (decimal, octal, hex or binary)
  30. * @param array<string, mixed> $attributes Additional attributes
  31. * @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5)
  32. *
  33. * @return Int_ The constructed LNumber, including kind attribute
  34. */
  35. public static function fromString(string $str, array $attributes = [], bool $allowInvalidOctal = false): Int_ {
  36. $attributes['rawValue'] = $str;
  37. $str = str_replace('_', '', $str);
  38. if ('0' !== $str[0] || '0' === $str) {
  39. $attributes['kind'] = Int_::KIND_DEC;
  40. return new Int_((int) $str, $attributes);
  41. }
  42. if ('x' === $str[1] || 'X' === $str[1]) {
  43. $attributes['kind'] = Int_::KIND_HEX;
  44. return new Int_(hexdec($str), $attributes);
  45. }
  46. if ('b' === $str[1] || 'B' === $str[1]) {
  47. $attributes['kind'] = Int_::KIND_BIN;
  48. return new Int_(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'] = Int_::KIND_OCT;
  59. return new Int_(intval($str, 8), $attributes);
  60. }
  61. public function getType(): string {
  62. return 'Scalar_Int';
  63. }
  64. }
  65. // @deprecated compatibility alias
  66. class_alias(Int_::class, LNumber::class);