LNumber.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  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($value, array $attributes = array()) {
  21. parent::__construct($attributes);
  22. $this->value = $value;
  23. }
  24. public function getSubNodeNames() {
  25. return array('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($str, array $attributes = array(), $allowInvalidOctal = false) {
  37. if ('0' !== $str[0] || '0' === $str) {
  38. $attributes['kind'] = LNumber::KIND_DEC;
  39. return new LNumber((int) $str, $attributes);
  40. }
  41. if ('x' === $str[1] || 'X' === $str[1]) {
  42. $attributes['kind'] = LNumber::KIND_HEX;
  43. return new LNumber(hexdec($str), $attributes);
  44. }
  45. if ('b' === $str[1] || 'B' === $str[1]) {
  46. $attributes['kind'] = LNumber::KIND_BIN;
  47. return new LNumber(bindec($str), $attributes);
  48. }
  49. if (!$allowInvalidOctal && strpbrk($str, '89')) {
  50. throw new Error('Invalid numeric literal', $attributes);
  51. }
  52. // use intval instead of octdec to get proper cutting behavior with malformed numbers
  53. $attributes['kind'] = LNumber::KIND_OCT;
  54. return new LNumber(intval($str, 8), $attributes);
  55. }
  56. }