Chris@13
|
1 <?php declare(strict_types=1);
|
Chris@0
|
2
|
Chris@0
|
3 namespace PhpParser\Node\Scalar;
|
Chris@0
|
4
|
Chris@0
|
5 use PhpParser\Error;
|
Chris@0
|
6 use PhpParser\Node\Scalar;
|
Chris@0
|
7
|
Chris@0
|
8 class LNumber extends Scalar
|
Chris@0
|
9 {
|
Chris@0
|
10 /* For use in "kind" attribute */
|
Chris@0
|
11 const KIND_BIN = 2;
|
Chris@0
|
12 const KIND_OCT = 8;
|
Chris@0
|
13 const KIND_DEC = 10;
|
Chris@0
|
14 const KIND_HEX = 16;
|
Chris@0
|
15
|
Chris@0
|
16 /** @var int Number value */
|
Chris@0
|
17 public $value;
|
Chris@0
|
18
|
Chris@0
|
19 /**
|
Chris@0
|
20 * Constructs an integer number scalar node.
|
Chris@0
|
21 *
|
Chris@0
|
22 * @param int $value Value of the number
|
Chris@0
|
23 * @param array $attributes Additional attributes
|
Chris@0
|
24 */
|
Chris@13
|
25 public function __construct(int $value, array $attributes = []) {
|
Chris@0
|
26 parent::__construct($attributes);
|
Chris@0
|
27 $this->value = $value;
|
Chris@0
|
28 }
|
Chris@0
|
29
|
Chris@13
|
30 public function getSubNodeNames() : array {
|
Chris@13
|
31 return ['value'];
|
Chris@0
|
32 }
|
Chris@0
|
33
|
Chris@0
|
34 /**
|
Chris@0
|
35 * Constructs an LNumber node from a string number literal.
|
Chris@0
|
36 *
|
Chris@0
|
37 * @param string $str String number literal (decimal, octal, hex or binary)
|
Chris@0
|
38 * @param array $attributes Additional attributes
|
Chris@0
|
39 * @param bool $allowInvalidOctal Whether to allow invalid octal numbers (PHP 5)
|
Chris@0
|
40 *
|
Chris@0
|
41 * @return LNumber The constructed LNumber, including kind attribute
|
Chris@0
|
42 */
|
Chris@13
|
43 public static function fromString(string $str, array $attributes = [], bool $allowInvalidOctal = false) : LNumber {
|
Chris@0
|
44 if ('0' !== $str[0] || '0' === $str) {
|
Chris@0
|
45 $attributes['kind'] = LNumber::KIND_DEC;
|
Chris@0
|
46 return new LNumber((int) $str, $attributes);
|
Chris@0
|
47 }
|
Chris@0
|
48
|
Chris@0
|
49 if ('x' === $str[1] || 'X' === $str[1]) {
|
Chris@0
|
50 $attributes['kind'] = LNumber::KIND_HEX;
|
Chris@0
|
51 return new LNumber(hexdec($str), $attributes);
|
Chris@0
|
52 }
|
Chris@0
|
53
|
Chris@0
|
54 if ('b' === $str[1] || 'B' === $str[1]) {
|
Chris@0
|
55 $attributes['kind'] = LNumber::KIND_BIN;
|
Chris@0
|
56 return new LNumber(bindec($str), $attributes);
|
Chris@0
|
57 }
|
Chris@0
|
58
|
Chris@0
|
59 if (!$allowInvalidOctal && strpbrk($str, '89')) {
|
Chris@0
|
60 throw new Error('Invalid numeric literal', $attributes);
|
Chris@0
|
61 }
|
Chris@0
|
62
|
Chris@0
|
63 // use intval instead of octdec to get proper cutting behavior with malformed numbers
|
Chris@0
|
64 $attributes['kind'] = LNumber::KIND_OCT;
|
Chris@0
|
65 return new LNumber(intval($str, 8), $attributes);
|
Chris@0
|
66 }
|
Chris@13
|
67
|
Chris@13
|
68 public function getType() : string {
|
Chris@13
|
69 return 'Scalar_LNumber';
|
Chris@13
|
70 }
|
Chris@0
|
71 }
|