Float_.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Node\Scalar;
  3. use PhpParser\Node\Scalar;
  4. class Float_ extends Scalar {
  5. /** @var float Number value */
  6. public float $value;
  7. /**
  8. * Constructs a float number scalar node.
  9. *
  10. * @param float $value Value of the number
  11. * @param array<string, mixed> $attributes Additional attributes
  12. */
  13. public function __construct(float $value, array $attributes = []) {
  14. $this->attributes = $attributes;
  15. $this->value = $value;
  16. }
  17. public function getSubNodeNames(): array {
  18. return ['value'];
  19. }
  20. /**
  21. * @param mixed[] $attributes
  22. */
  23. public static function fromString(string $str, array $attributes = []): Float_ {
  24. $attributes['rawValue'] = $str;
  25. $float = self::parse($str);
  26. return new Float_($float, $attributes);
  27. }
  28. /**
  29. * @internal
  30. *
  31. * Parses a DNUMBER token like PHP would.
  32. *
  33. * @param string $str A string number
  34. *
  35. * @return float The parsed number
  36. */
  37. public static function parse(string $str): float {
  38. $str = str_replace('_', '', $str);
  39. // Check whether this is one of the special integer notations.
  40. if ('0' === $str[0]) {
  41. // hex
  42. if ('x' === $str[1] || 'X' === $str[1]) {
  43. return hexdec($str);
  44. }
  45. // bin
  46. if ('b' === $str[1] || 'B' === $str[1]) {
  47. return bindec($str);
  48. }
  49. // oct, but only if the string does not contain any of '.eE'.
  50. if (false === strpbrk($str, '.eE')) {
  51. // substr($str, 0, strcspn($str, '89')) cuts the string at the first invalid digit
  52. // (8 or 9) so that only the digits before that are used.
  53. return octdec(substr($str, 0, strcspn($str, '89')));
  54. }
  55. }
  56. // dec
  57. return (float) $str;
  58. }
  59. public function getType(): string {
  60. return 'Scalar_Float';
  61. }
  62. }
  63. // @deprecated compatibility alias
  64. class_alias(Float_::class, DNumber::class);