Debian Codegraph @

vendor/wikimedia/parsoid/src/Utils/PHPUtils.php

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Utils;
5
6 use Wikimedia\Assert\Assert;
7 use Wikimedia\Assert\UnreachableException;
8
9 /**
10 * This file contains Parsoid-independent PHP helper functions.
11 * Over time, more functions can be migrated out of various other files here.
12 * @module
13 */
14
15 class PHPUtils {
16 /**
17 * Convert a counter to a Base64 encoded string.
18 * Padding is stripped. /,+ are replaced with _,- respectively.
19 * Warning: Max integer is 2^31 - 1 for bitwise operations.
20 * @param int $n
21 * @return string
22 */
23 public static function counterToBase64( int $n ): string {
24 $str = '';
25 do {
26 $str = chr( $n & 0xff ) . $str;
27 $n >>= 8;
28 } while ( $n > 0 );
29 return rtrim( strtr( base64_encode( $str ), '+/', '-_' ), '=' );
30 }
31
32 /**
33 * FIXME: Copied from FormatJson.php in core
34 *
35 * Characters problematic in JavaScript.
36 *
37 * @note These are listed in ECMA-262 (5.1 Ed.), ยง7.3 Line Terminators along with U+000A (LF)
38 * and U+000D (CR). However, PHP already escapes LF and CR according to RFC 4627.
39 */
40 private const BAD_CHARS = [
41 "\u{2028}", // U+2028 LINE SEPARATOR
42 "\u{2029}", // U+2029 PARAGRAPH SEPARATOR
43 ];
44
45 /**
46 * FIXME: Copied from FormatJson.php in core
47 *
48 * Escape sequences for characters listed in FormatJson::BAD_CHARS.
49 */
50 private const BAD_CHARS_ESCAPED = [
51 '\u2028', // U+2028 LINE SEPARATOR
52 '\u2029', // U+2029 PARAGRAPH SEPARATOR
53 ];
54
55 /**
56 * FIXME: Core has FormatJson::encode that does a more comprehensive job
57 *
58 * json_encode wrapper function
59 * - unscapes slashes and unicode
60 *
61 * @param mixed $o
62 * @return string
63 */
64 public static function jsonEncode( $o ): string {
65 $str = json_encode( $o, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR );
66 $str = str_replace( self::BAD_CHARS, self::BAD_CHARS_ESCAPED, $str );
67 return $str;
68 }
69
70 /**
71 * FIXME: Core has FormatJson::parse that does a more comprehensive job
72 * json_decode wrapper function
73 * @param string $str String to decode into the json object
74 * @param bool $assoc Controls whether to parse as an an associative array - defaults to true
75 * @return mixed
76 */
77 public static function jsonDecode( string $str, bool $assoc = true ) {
78 return json_decode( $str, $assoc );
79 }
80
81 /**
82 * Convert array to associative array usable as a read-only Set.
83 *
84 * @param array $a
85 * @return array
86 */
87 public static function makeSet( array $a ): array {
88 return array_fill_keys( $a, true );
89 }
90
91 /**
92 * Helper to get last item of the array
93 * @param mixed[] $a
94 * @return mixed
95 */
96 public static function lastItem( array $a ) {
97 // Tim Starling recommends not using end() for perf reasons
98 // since apparently it can be O(n) where the refcount on the
99 // array is > 1.
100 //
101 // Note that end() is usable in non-array scenarios. But, in our case,
102 // we are almost always dealing with arrays, so this helper probably
103 // better for cases where we aren't sure the array isn't shared.
104 return $a[count( $a ) - 1] ?? null;
105 }
106
107 /**
108 * Append an array to an accumulator using the most efficient method
109 * available. Makes sure that accumulation is O(n).
110 *
111 * See https://w.wiki/3zvE
112 *
113 * @param array &$dest Destination array
114 * @param array $source Array to merge
115 */
116 public static function pushArray( array &$dest, array $source ): void {
117 if ( count( $dest ) < count( $source ) ) {
118 $dest = array_merge( $dest, $source );
119 } else {
120 foreach ( $source as $item ) {
121 $dest[] = $item;
122 }
123 }
124 }
125
126 /**
127 * Return a substring, asserting that it is valid UTF-8.
128 * By default we assume the full string was valid UTF-8, which allows
129 * us to look at the first and last bytes to make this check.
130 * You can check the entire string if you are feeling paranoid; it
131 * will take O(N) time (where N is the length of the substring) but
132 * so does the substring operation.
133 *
134 * If the substring would start beyond the end of the string or
135 * end before the start of the string, then this function will
136 * return the empty string (as would JavaScript); note that the
137 * native `substr` would return `false` in this case.
138 *
139 * Using this helper instead of native `substr` is
140 * useful during the PHP port to verify that we don't break up
141 * Unicode codepoints by the switch from JavaScript UCS-2 offsets
142 * to PHP UTF-8 byte offsets.
143 *
144 * @param string $s The (sub)string to check
145 * @param int $start The starting offset (in bytes). If negative, the
146 * offset is counted from the end of the string.
147 * @param ?int $length (optional) The maximum length of the returned
148 * string. If negative, the end position is counted from the end of
149 * the string.
150 * @param bool $checkEntireString Whether to do a slower verification
151 * of the entire string, not just the edges. Defaults to false.
152 * @return string The checked substring
153 */
154 public static function safeSubstr(
155 string $s, int $start, ?int $length = null,
156 bool $checkEntireString = false
157 ): string {
158 if ( $length === null ) {
159 $ss = substr( $s, $start );
160 } else {
161 $ss = substr( $s, $start, $length );
162 }
163 if ( $ss === '' ) {
164 return $ss;
165 }
166 $firstChar = ord( $ss[0] );
167 Assert::invariant(
168 ( $firstChar & 0xC0 ) !== 0x80,
169 'Bad UTF-8 at start of string'
170 );
171 $i = 0;
172 // This next loop won't step off the front of the string because we've
173 // already asserted that the first character is not 10xx xxxx
174 do {
175 $i--;
176 Assert::invariant(
177 $i > -5,
178 // This should never happen, assuming the original string
179 // was valid UTF-8
180 'Bad UTF-8 at end of string (>4 byte sequence)'
181 );
182 $lastChar = ord( $ss[$i] );
183 } while ( ( $lastChar & 0xC0 ) === 0x80 );
184 if ( ( $lastChar & 0x80 ) === 0 ) {
185 Assert::invariant(
186 // This shouldn't happen, assuming original string was valid
187 $i === -1, 'Bad UTF-8 at end of string (1 byte sequence)'
188 );
189 } elseif ( ( $lastChar & 0xE0 ) === 0xC0 ) {
190 Assert::invariant(
191 $i === -2, 'Bad UTF-8 at end of string (2 byte sequence)'
192 );
193 } elseif ( ( $lastChar & 0xF0 ) === 0xE0 ) {
194 Assert::invariant(
195 $i === -3, 'Bad UTF-8 at end of string (3 byte sequence)'
196 );
197 } elseif ( ( $lastChar & 0xF8 ) === 0xF0 ) {
198 Assert::invariant(
199 $i === -4, 'Bad UTF-8 at end of string (4 byte sequence)'
200 );
201 } else {
202 throw new UnreachableException(
203 // This shouldn't happen, assuming original string was valid
204 'Bad UTF-8 at end of string'
205 );
206 }
207 if ( $checkEntireString ) {
208 // We did the head/tail checks first because they give better
209 // diagnostics in the common case where we broke UTF-8 by
210 // the substring operation.
211 self::assertValidUTF8( $ss );
212 }
213 return $ss;
214 }
215
216 /**
217 * Helper for verifying a valid UTF-8 encoding. Using
218 * safeSubstr() is a more efficient way of doing this check in
219 * most places, where you can assume that the original string was
220 * valid UTF-8. This function does a complete traversal of the
221 * string, in time proportional to the length of the string.
222 *
223 * @param string $s The string to check.
224 */
225 public static function assertValidUTF8( string $s ): void {
226 // Slow complete O(N) check for UTF-8 validity
227 $r = preg_match( '//u', $s );
228 Assert::invariant(
229 $r === 1,
230 'Bad UTF-8 (full string verification)'
231 );
232 }
233
234 /**
235 * Helper for joining pieces of regular expressions together. This
236 * safely strips delimiters from regular expression strings, while
237 * ensuring that the result is safely escaped for the new delimiter
238 * you plan to use (see the `$delimiter` argument to `preg_quote`).
239 * Note that using a meta-character for the new delimiter can lead to
240 * unexpected results; for example, if you use `!` then escaping
241 * `(?!foo)` will break the regular expression.
242 *
243 * @param string $re The regular expression to strip
244 * @param ?string $newDelimiter Optional delimiter which will be
245 * used when recomposing this stripped regular expression into a
246 * new regular expression.
247 * @return string The regular expression without delimiters or flags
248 */
249 public static function reStrip(
250 string $re, ?string $newDelimiter = null
251 ): string {
252 static $delimiterPairs = [
253 '(' => ')',
254 '[' => ']',
255 '{' => '}',
256 '<' => '>',
257 ];
258 // Believe it or not, PHP allows leading whitespace in the $re
259 // tested with C's "isspace", which is [ \f\n\r\t\v]
260 $re = preg_replace( '/^[ \f\n\r\t\v]+/', '', $re );
261 Assert::invariant( strlen( $re ) > 0, "empty regexp" );
262 $startDelimiter = $re[0];
263 // PHP actually supports balanced delimiters (ie open paren on left
264 // and close paren on right).
265 $endDelimiter = $delimiterPairs[$startDelimiter] ?? $startDelimiter;
266 $endDelimiterPos = strrpos( $re, $endDelimiter );
267 Assert::invariant(
268 $endDelimiterPos !== false && $endDelimiterPos > 0,
269 "can't find end delimiter"
270 );
271 $flags = substr( $re, $endDelimiterPos + 1 );
272 Assert::invariant(
273 preg_match( '/^[imsxADSUXJu \n]*$/D', $flags ) === 1,
274 "unexpected flags"
275 );
276 $stripped = substr( $re, 1, $endDelimiterPos - 1 );
277 if (
278 $newDelimiter === null ||
279 $startDelimiter === $newDelimiter ||
280 $endDelimiter === $newDelimiter
281 ) {
282 return $stripped; // done!
283 }
284 $newCloseDelimiter = $delimiterPairs[$startDelimiter] ?? $startDelimiter;
285 // escape the new delimiter
286 preg_match_all( '/[^\\\\]|\\\\./s', $stripped, $matches );
287 return implode( '', array_map( static function ( $c ) use ( $newDelimiter, $newCloseDelimiter ) {
288 return ( $c === $newDelimiter || $c === $newCloseDelimiter )
289 ? ( '\\' . $c ) : $c;
290 }, $matches[0] ) );
291 }
292
293 /**
294 * JS-compatible encodeURIComponent function
295 * FIXME: See T221147 (for a post-port update)
296 *
297 * @param string $str
298 * @return string
299 */
300 public static function encodeURIComponent( string $str ): string {
301 $revert = [ '%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')' ];
302 return strtr( rawurlencode( $str ), $revert );
303 }
304
305 /**
306 * Sort keys in an array, recursively, for better reproducibility.
307 * (This is especially useful before serializing as JSON.)
308 *
309 * @param mixed &$array
310 */
311 public static function sortArray( &$array ): void {
312 if ( !is_array( $array ) ) {
313 return;
314 }
315 ksort( $array );
316 foreach ( $array as $k => $v ) {
317 self::sortArray( $array[$k] );
318 }
319 }
320
321 /**
322 * Convert an iterable to an array.
323 *
324 * This function is similar to *but not the same as* the built-in
325 * iterator_to_array, because arrays are iterable but not Traversable!
326 *
327 * This function is also present in the wmde/iterable-functions library,
328 * but it's short enough that we don't need to pull in an entire new
329 * dependency here.
330 *
331 * @see https://stackoverflow.com/questions/44587973/php-iterable-to-array-or-traversable
332 * @see https://github.com/wmde/iterable-functions/blob/master/src/functions.php
333 *
334 * @phan-template T
335 * @param iterable<T> $iterable
336 * @return array<T>
337 */
338 public static function iterable_to_array( iterable $iterable ): array { // phpcs:ignore MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName,Generic.Files.LineLength.TooLong
339 if ( is_array( $iterable ) ) {
340 return $iterable;
341 }
342 '@phan-var \Traversable $iterable'; // @var \Traversable $iterable
343 return iterator_to_array( $iterable );
344 }
345
346 /**
347 * Indicate that the code which calls this function is intended to be
348 * unreachable.
349 *
350 * This is a workaround for T247093; this has been moved upstream
351 * into wikimedia/assert.
352 *
353 * @param string $reason
354 * @return never
355 * @deprecated Just throw an UnreachableException instead.
356 */
357 public static function unreachable( string $reason = "should never happen" ) {
358 throw new UnreachableException( $reason );
359 }
360
361 /**
362 * If a string starts with a given prefix, remove the prefix. Otherwise,
363 * return the original string. Like preg_replace( "/^$prefix/", '', $subject )
364 * except about 1.14x faster in the replacement case and 2x faster in
365 * the no-op case.
366 *
367 * Note: adding type declarations to the parameters adds an overhead of 3%.
368 * The benchmark above was without type declarations.
369 *
370 * @param string $subject
371 * @param string $prefix
372 * @return string
373 */
374 public static function stripPrefix( $subject, $prefix ) {
375 if ( str_starts_with( $subject, $prefix ) ) {
376 return substr( $subject, strlen( $prefix ) );
377 } else {
378 return $subject;
379 }
380 }
381
382 /**
383 * If a string ends with a given suffix, remove the suffix. Otherwise,
384 * return the original string. Like preg_replace( "/$suffix$/", '', $subject )
385 * except faster.
386 *
387 * @param string $subject
388 * @param string $suffix
389 * @return string
390 */
391 public static function stripSuffix( $subject, $suffix ) {
392 if ( str_ends_with( $subject, $suffix ) ) {
393 return substr( $subject, 0, -strlen( $suffix ) );
394 } else {
395 return $subject;
396 }
397 }
398
399 }