Debian Codegraph @

vendor/mck89/peast/lib/Peast/Syntax/Utils.php

raw
1 <?php
2 /**
3 * This file is part of the Peast package
4 *
5 * (c) Marco Marchiò <[email protected]>
6 *
7 * For the full copyright and license information refer to the LICENSE file
8 * distributed with this source code
9 */
10 namespace Peast\Syntax;
11
12 /**
13 * Utilities class.
14 *
15 * @author Marco Marchiò <[email protected]>
16 */
17 class Utils
18 {
19 /**
20 * Converts a string to an array of UTF-8 characters
21 *
22 * @param string $str String to convert
23 * @param bool $strictEncoding If false and the string contains invalid
24 * UTF-8 characters, it will replace those
25 * characters with the one defined in the
26 * mbstring.substitute_character setting
27 *
28 * @return array
29 *
30 * @throws EncodingException
31 */
32 static public function stringToUTF8Array($str, $strictEncoding = true)
33 {
34 if ($str === "") {
35 return array();
36 }
37 $ret = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
38 if (preg_last_error() === PREG_BAD_UTF8_ERROR) {
39 if (!$strictEncoding) {
40 $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
41 $ret = self::stringToUTF8Array($str, false);
42 } else {
43 throw new EncodingException("String contains invalid UTF-8");
44 }
45 }
46 return $ret;
47 }
48
49 /**
50 * Converts an unicode code point to UTF-8
51 *
52 * @param int $num Unicode code point
53 *
54 * @return string
55 *
56 * @codeCoverageIgnore
57 */
58 static public function unicodeToUtf8($num)
59 {
60 //From: http://stackoverflow.com/questions/1805802/php-convert-unicode-codepoint-to-utf-8#answer-7153133
61 if ($num <= 0x7F) {
62 return chr($num);
63 } elseif ($num <= 0x7FF) {
64 return chr(($num >> 6) + 192) .
65 chr(($num & 63) + 128);
66 } elseif ($num <= 0xFFFF) {
67 return chr(($num >> 12) + 224) .
68 chr((($num >> 6) & 63) + 128) .
69 chr(($num & 63) + 128);
70 } elseif ($num <= 0x1FFFFF) {
71 return chr(($num >> 18) + 240) .
72 chr((($num >> 12) & 63) + 128) .
73 chr((($num >> 6) & 63) + 128) .
74 chr(($num & 63) + 128);
75 }
76 return '';
77 }
78
79 /**
80 * Compiled line terminators cache
81 *
82 * @var array
83 */
84 protected static $lineTerminatorsCache;
85
86 /**
87 * Returns line terminators array
88 *
89 * @return array
90 */
91 protected static function getLineTerminators()
92 {
93 if (!self::$lineTerminatorsCache) {
94 self::$lineTerminatorsCache = array();
95 foreach (Scanner::$lineTerminatorsChars as $char) {
96 self::$lineTerminatorsCache[] = is_int($char) ?
97 self::unicodeToUtf8($char) :
98 $char;
99 }
100 }
101 return self::$lineTerminatorsCache;
102 }
103
104 /**
105 * Converts a surrogate pair of Unicode code points to UTF-8
106 *
107 * @param string $first First Unicode code point
108 * @param string $second Second Unicode code point
109 *
110 * @return string
111 *
112 * @codeCoverageIgnore
113 */
114 static public function surrogatePairToUtf8($first, $second)
115 {
116 //From: https://stackoverflow.com/questions/39226593/how-to-convert-utf16-surrogate-pairs-to-equivalent-hex-codepoint-in-php
117 $value = ((hexdec($first) & 0x3ff) << 10) | (hexdec($second) & 0x3ff);
118 return self::unicodeToUtf8($value + 0x10000);
119 }
120
121 /**
122 * This function takes a string as it appears in the source code and returns
123 * an unquoted version of it
124 *
125 * @param string $str The string to unquote
126 *
127 * @return string
128 */
129 static public function unquoteLiteralString($str)
130 {
131 //Remove quotes
132 $str = substr($str, 1, -1);
133
134 //Return immediately if the escape character is missing
135 if (strpos($str, "\\") === false) {
136 return $str;
137 }
138
139 $lineTerminators = self::getLineTerminators();
140
141 //Surrogate pairs regex
142 $surrogatePairsReg = sprintf(
143 'u(?:%1$s|\{%1$s\})\\\\u(?:%2$s|\{%2$s\})',
144 "[dD][89abAB][0-9a-fA-F]{2}", "[dD][c-fC-F][0-9a-fA-F]{2}"
145 );
146
147 //Handle escapes
148 $patterns = array(
149 $surrogatePairsReg,
150 "u\{[a-fA-F0-9]+\}",
151 "u[a-fA-F0-9]{4}",
152 "x[a-fA-F0-9]{2}",
153 "0[0-7]{2}",
154 "[1-7][0-7]",
155 "."
156 );
157 $reg = "/\\\\(" . implode("|", $patterns) . ")/s";
158 $simpleSequence = array(
159 "n" => "\n",
160 "f" => "\f",
161 "r" => "\r",
162 "t" => "\t",
163 "v" => "\v",
164 "b" => "\x8"
165 );
166 $replacement = function ($m) use ($simpleSequence, $lineTerminators) {
167 $type = $m[1][0];
168 if (isset($simpleSequence[$type])) {
169 // \n, \r, \t ...
170 return $simpleSequence[$type];
171 } elseif ($type === "u" || $type === "x") {
172 //Invalid unicode or hexadecimal sequences
173 if (strlen($m[1]) === 1) {
174 return "\\$type";
175 }
176 // Surrogate pair
177 if ($type === "u" && strpos($m[1], "\\") !== false) {
178 $points = explode("\\", $m[1]);
179 return Utils::surrogatePairToUtf8(
180 str_replace(array("{", "}", "u"), "", $points[0]),
181 str_replace(array("{", "}", "u"), "", $points[1])
182 );
183 }
184 // \uFFFF, \u{FFFF}, \xFF
185 $code = substr($m[1], 1);
186 $code = str_replace(array("{", "}"), "", $code);
187 return Utils::unicodeToUtf8(hexdec($code));
188 } elseif ($type >= "0" && $type <= "7") {
189 //Invalid octal sequences
190 if (strlen($m[1]) === 1) {
191 return "\\$type";
192 }
193 // \123
194 return Utils::unicodeToUtf8(octdec($m[1]));
195 } elseif (in_array($m[1], $lineTerminators)) {
196 // Escaped line terminators
197 return "";
198 } else {
199 // Escaped characters
200 return $m[1];
201 }
202 };
203 return preg_replace_callback($reg, $replacement, $str);
204 }
205
206 /**
207 * This function converts a string to a quoted javascript string
208 *
209 * @param string $str String to quote
210 * @param string $quote Quote character
211 *
212 * @return string
213 */
214 static public function quoteLiteralString($str, $quote)
215 {
216 $escape = self::getLineTerminators();
217 $escape[] = $quote;
218 $escape[] = "\\\\";
219 $reg = "/(" . implode("|", $escape) . ")/";
220 $str = preg_replace($reg, "\\\\$1", $str);
221 return $quote . $str . $quote;
222 }
223
224 /**
225 * Returns the properties map for the given node
226 *
227 * @param mixed $node Node or class to consider
228 *
229 * @return array
230 */
231 static protected function getPropertiesMap($node)
232 {
233 static $cache = array();
234
235 if ($node instanceof \ReflectionClass) {
236 $className = $node->getName();
237 } else {
238 $className = get_class($node);
239 }
240
241 if (!isset($cache[$className])) {
242 $class = new \ReflectionClass($className);
243 $parent = $class->getParentClass();
244 $props = $parent ? self::getPropertiesMap($parent) : array();
245 $defaults = $class->getDefaultProperties();
246 if (isset($defaults["propertiesMap"])) {
247 $props = array_merge($props, $defaults["propertiesMap"]);
248 }
249 $cache[$className] = $props;
250 }
251 return $cache[$className];
252 }
253
254 /**
255 * Returns the properties list for the given node
256 *
257 * @param Node\Node $node Node to consider
258 * @param bool $traversable If true it returns only traversable properties
259 *
260 * @return array
261 */
262 static public function getNodeProperties(Node\Node $node, $traversable = false)
263 {
264 $props = self::getPropertiesMap($node);
265 return array_map(
266 function ($prop) {
267 $ucProp = ucfirst($prop);
268 return array(
269 "name" => $prop,
270 "getter" => "get$ucProp",
271 "setter" => "set$ucProp"
272 );
273 },
274 array_keys($traversable ? array_filter($props) : $props)
275 );
276 }
277
278 /**
279 * Returns an expanded version of the traversable node properties.
280 * The return of the function is an array of node properties
281 * values with arrays flattened
282 *
283 * @param Node\Node $node Node
284 *
285 * @return array
286 */
287 static public function getExpandedNodeProperties(Node\Node $node)
288 {
289 $ret = array();
290 $props = self::getNodeProperties($node, true);
291 foreach ($props as $prop) {
292 $val = $node->{$prop["getter"]}();
293 if (is_array($val)) {
294 $ret = array_merge($ret, $val);
295 } else {
296 $ret[] = $val;
297 }
298 }
299 return $ret;
300 }
301
302 /**
303 * Delete an array element by value
304 *
305 * @param array $array Array
306 * @param mixed $val Value to remove
307 *
308 * @return void
309 */
310 static public function removeArrayValue(&$array, $val)
311 {
312 array_splice($array, array_search($val, $array), 1);
313 }
314 }