-
-
Notifications
You must be signed in to change notification settings - Fork 589
/
TypeVisitor.php
75 lines (61 loc) · 1.93 KB
/
TypeVisitor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace JMS\Serializer\Type;
use Hoa\Compiler\Llk\TreeNode;
use Hoa\Visitor\Element;
use Hoa\Visitor\Visit;
use JMS\Serializer\Type\Exception\InvalidNode;
use function strpos;
final class TypeVisitor implements Visit
{
/**
* {@inheritdoc}
*/
public function visit(Element $element, &$handle = null, $eldnah = null)
{
switch ($element->getId()) {
case '#simple_type':
return $this->visitSimpleType($element);
case '#compound_type':
return $this->visitCompoundType($element, $handle, $eldnah);
}
throw new InvalidNode();
}
/**
* @return string|mixed[]
*/
private function visitSimpleType(TreeNode $element)
{
$tokenNode = $element->getChild(0);
$token = $tokenNode->getValueToken();
$value = $tokenNode->getValueValue();
if ('name' === $token) {
return ['name' => $value, 'params' => []];
}
if ('empty_string' === $token) {
return '';
}
if ('number' === $token) {
return false === strpos($value, '.') ? intval($value) : floatval($value);
}
$escapeChar = 'quoted_string' === $token ? '"' : "'";
if (false === strpos($value, $escapeChar)) {
return $value;
}
return str_replace($escapeChar . $escapeChar, $escapeChar, $value);
}
private function visitCompoundType(TreeNode $element, ?int &$handle, ?int $eldnah): array
{
$nameToken = $element->getChild(0);
$parameters = array_slice($element->getChildren(), 1);
return [
'name' => $nameToken->getValueValue(),
'params' => array_map(
function (TreeNode $node) use ($handle, $eldnah) {
return $node->accept($this, $handle, $eldnah);
},
$parameters
),
];
}
}