|
1
|
|
|
<?php |
|
2
|
|
|
|
|
|
|
|
|
|
3
|
|
|
namespace Dallgoot\Yaml; |
|
4
|
|
|
|
|
5
|
|
|
use Dallgoot\Yaml\{Yaml as Y, Regex as R}; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* TODO |
|
9
|
|
|
* |
|
10
|
|
|
* @author Stéphane Rebai <[email protected]> |
|
11
|
|
|
* @license Apache 2.0 |
|
12
|
|
|
* @link TODO : url to specific online doc |
|
13
|
|
|
*/ |
|
|
|
|
|
|
14
|
|
|
final class Node2PHP |
|
15
|
|
|
{ |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Returns the correct PHP datatype for the value of the current Node |
|
19
|
|
|
* |
|
20
|
|
|
* @param Node $n a Node object to be evaluated as PHP type. |
|
21
|
|
|
* @return mixed The value as PHP type : scalar, array or Compact, DateTime |
|
|
|
|
|
|
22
|
|
|
* @throws \Exception if occurs in self::getScalar or self::getCompact |
|
|
|
|
|
|
23
|
|
|
*/ |
|
24
|
|
|
public static function get(Node $n) |
|
25
|
|
|
{ |
|
26
|
|
|
if (is_null($n->value)) return null; |
|
27
|
|
|
if ($n->type & (Y::REF_CALL | Y::SCALAR)) return self::getScalar($n->value); |
|
|
|
|
|
|
28
|
|
|
if ($n->type & Y::JSON) { |
|
29
|
|
|
return $n->value; |
|
30
|
|
|
} |
|
31
|
|
|
$expected = [Y::QUOTED => trim($n->value, "\"'"), |
|
|
|
|
|
|
32
|
|
|
Y::RAW => strval($n->value)]; |
|
33
|
|
|
return $expected[$n->type] ?? null; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
/** |
|
37
|
|
|
* Returns the correct PHP type according to the string value |
|
38
|
|
|
* |
|
39
|
|
|
* @param string $v a string value |
|
40
|
|
|
* |
|
41
|
|
|
* @return mixed The value with appropriate PHP type |
|
42
|
|
|
* @throws \Exception if happens in R::isDate or R::isNumber |
|
43
|
|
|
*/ |
|
44
|
|
|
private static function getScalar(string $v) |
|
|
|
|
|
|
45
|
|
|
{ |
|
46
|
|
|
if (R::isDate($v)) return date_create($v); |
|
47
|
|
|
if (R::isNumber($v)) return self::getNumber($v); |
|
48
|
|
|
$types = ['yes' => true, |
|
49
|
|
|
'no' => false, |
|
50
|
|
|
'true' => true, |
|
51
|
|
|
'false' => false, |
|
52
|
|
|
'null' => null, |
|
53
|
|
|
'.inf' => INF, |
|
54
|
|
|
'-.inf' => -INF, |
|
55
|
|
|
'.nan' => NAN |
|
56
|
|
|
]; |
|
57
|
|
|
return array_key_exists(strtolower($v), $types) ? $types[strtolower($v)] : strval($v); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Returns the correct PHP type according to the string value |
|
62
|
|
|
* |
|
63
|
|
|
* @param string $v a string value |
|
64
|
|
|
* |
|
65
|
|
|
* @return int|float The scalar value with appropriate PHP type |
|
66
|
|
|
*/ |
|
67
|
|
|
private static function getNumber(string $v) |
|
|
|
|
|
|
68
|
|
|
{ |
|
69
|
|
|
if (preg_match("/^(0o\d+)$/i", $v)) return intval(base_convert($v, 8, 10)); |
|
70
|
|
|
if (preg_match("/^(0x[\da-f]+)$/i", $v)) return intval(base_convert($v, 16, 10)); |
|
71
|
|
|
return is_bool(strpos($v, '.')) ? intval($v) : floatval($v); |
|
|
|
|
|
|
72
|
|
|
} |
|
73
|
|
|
} |