Debian Codegraph @

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

raw
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Wikimedia\Parsoid\Ext;
5
6 use Wikimedia\Parsoid\Utils\PHPUtils as PHPU;
7
8 /**
9 * This class contains sundry helpers unrelated to core Parsoid
10 */
11 class PHPUtils {
12
13 /**
14 * Convert an iterable to an array.
15 *
16 * This function is similar to *but not the same as* the built-in
17 * iterator_to_array, because arrays are iterable but not Traversable!
18 *
19 * This function is also present in the wmde/iterable-functions library,
20 * but it's short enough that we don't need to pull in an entire new
21 * dependency here.
22 *
23 * @see https://stackoverflow.com/questions/44587973/php-iterable-to-array-or-traversable
24 * @see https://github.com/wmde/iterable-functions/blob/master/src/functions.php
25 *
26 * @phan-template T
27 * @param iterable<T> $iterable
28 * @return array<T>
29 */
30 public static function iterable_to_array( iterable $iterable ): array { // phpcs:ignore MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName,Generic.Files.LineLength.TooLong
31 return PHPU::iterable_to_array( $iterable );
32 }
33
34 /**
35 * json_encode wrapper function
36 * - unscapes slashes and unicode
37 *
38 * @param mixed $o
39 * @return string
40 */
41 public static function jsonEncode( $o ): string {
42 return PHPU::jsonEncode( $o );
43 }
44
45 /**
46 * If a string starts with a given prefix, remove the prefix. Otherwise,
47 * return the original string. Like preg_replace( "/^$prefix/", '', $subject )
48 * except about 1.14x faster in the replacement case and 2x faster in
49 * the no-op case.
50 *
51 * Note: adding type declarations to the parameters adds an overhead of 3%.
52 * The benchmark above was without type declarations.
53 *
54 * @param string $subject
55 * @param string $prefix
56 * @return string
57 */
58 public static function stripPrefix( $subject, $prefix ) {
59 return PHPU::stripPrefix( $subject, $prefix );
60 }
61
62 /**
63 * If a string ends with a given suffix, remove the suffix. Otherwise,
64 * return the original string. Like preg_replace( "/$suffix$/", '', $subject )
65 * except faster.
66 *
67 * @param string $subject
68 * @param string $suffix
69 * @return string
70 */
71 public static function stripSuffix( $subject, $suffix ) {
72 return PHPU::stripSuffix( $subject, $suffix );
73 }
74
75 }