DNumber.php 1.6 KB

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