1: <?php
2: namespace Pharborist\Types;
3:
4: use Pharborist\ExpressionNode;
5: use Pharborist\TokenNode;
6:
7: 8: 9: 10: 11: 12: 13:
14: class StringNode extends TokenNode implements ExpressionNode, ScalarNode {
15: 16: 17: 18: 19: 20: 21: 22:
23: public static function create($text) {
24: return new StringNode(T_CONSTANT_ENCAPSED_STRING, $text);
25: }
26:
27: 28: 29: 30: 31:
32: public function toValue() {
33: $text = $this->getText();
34: $quote_char = $text[0];
35: $text = substr($text, 1, -1);
36: if ($quote_char === '"') {
37: $rules = array(
38: preg_quote('\\\\') => '\\',
39: preg_quote('\n') => "\n",
40: preg_quote('\t') => "\t",
41: preg_quote('\"') => '"',
42: preg_quote('\$') => '$',
43: preg_quote('\r') => "\r",
44: preg_quote('\v') => "\v",
45: preg_quote('\f') => "\f",
46: preg_quote('\e') => "\e",
47: '\\\\[0-7]{1,3}' => '__octal__',
48: '\\\\x[0-9A-Fa-f]{1,2}' => '__hex__',
49: );
50: }
51: else {
52: $rules = array(
53: preg_quote('\\\\') => '\\',
54: preg_quote("\\'") => "'"
55: );
56: }
57: $replacements = array_values($rules);
58: $regex = '@(' . implode(')|(', array_keys($rules)) . ')@';
59: return preg_replace_callback($regex, function ($matches) use ($replacements) {
60:
61: for ($i = 1; '' === $matches[$i]; ++$i);
62:
63: $match = $matches[0];
64: $replacement = $replacements[$i - 1];
65: if ($replacement === '__octal__') {
66: $replacement = chr(octdec(substr($match, 1)));
67: }
68: elseif ($replacement === '__hex__') {
69: $replacement = chr(hexdec(substr($match, 2)));
70: }
71: return $replacement;
72: }, $text);
73: }
74: }
75: