DNumber.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Scalar;
  3. use PhpParser\Node\Scalar;
  4. class DNumber extends Scalar
  5. {
  6. /** @var float Number value */
  7. public $value;
  8. /**
  9. * Constructs a float number scalar node.
  10. *
  11. * @param float $value Value of the number
  12. * @param array $attributes Additional attributes
  13. */
  14. public function __construct(float $value, array $attributes = []) {
  15. parent::__construct($attributes);
  16. $this->value = $value;
  17. }
  18. public function getSubNodeNames() : array {
  19. return ['value'];
  20. }
  21. /**
  22. * @internal
  23. *
  24. * Parses a DNUMBER token like PHP would.
  25. *
  26. * @param string $str A string number
  27. *
  28. * @return float The parsed number
  29. */
  30. public static function parse(string $str) : float {
  31. // if string contains any of .eE just cast it to float
  32. if (false !== strpbrk($str, '.eE')) {
  33. return (float) $str;
  34. }
  35. // otherwise it's an integer notation that overflowed into a float
  36. // if it starts with 0 it's one of the special integer notations
  37. if ('0' === $str[0]) {
  38. // hex
  39. if ('x' === $str[1] || 'X' === $str[1]) {
  40. return hexdec($str);
  41. }
  42. // bin
  43. if ('b' === $str[1] || 'B' === $str[1]) {
  44. return bindec($str);
  45. }
  46. // oct
  47. // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit (8 or 9)
  48. // so that only the digits before that are used
  49. return octdec(substr($str, 0, strcspn($str, '89')));
  50. }
  51. // dec
  52. return (float) $str;
  53. }
  54. public function getType() : string {
  55. return 'Scalar_DNumber';
  56. }
  57. }