Completed
Branch master (d58858)
by
unknown
28:23
created

StringUtils::isUtf8()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 7
nc 6
nop 1
1
<?php
2
/**
3
 * Methods to play with strings.
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 */
22
23
/**
24
 * A collection of static methods to play with strings.
25
 */
26
class StringUtils {
27
	/**
28
	 * Test whether a string is valid UTF-8.
29
	 *
30
	 * The function check for invalid byte sequences, overlong encoding but
31
	 * not for different normalisations.
32
	 *
33
	 * @note In MediaWiki 1.21, this function did not provide proper UTF-8 validation.
34
	 * In particular, the pure PHP code path did not in fact check for overlong forms.
35
	 * Beware of this when backporting code to that version of MediaWiki.
36
	 *
37
	 * @since 1.21
38
	 * @param string $value String to check
39
	 * @return bool Whether the given $value is a valid UTF-8 encoded string
40
	 */
41
	static function isUtf8( $value ) {
42
		$value = (string)$value;
43
44
		// Before PHP 5.4, values above U+10FFFF are incorrectly allowed, so we have to
45
		// check for them separately.
46
		static $newPHP;
47
		if ( $newPHP === null ) {
48
			$newPHP = !mb_check_encoding( "\xf4\x90\x80\x80", 'UTF-8' );
49
		}
50
51
		return mb_check_encoding( $value, 'UTF-8' ) &&
52
			( $newPHP || preg_match( "/\xf4[\x90-\xbf]|[\xf5-\xff]/S", $value ) === 0 );
53
	}
54
55
	/**
56
	 * Perform an operation equivalent to `preg_replace()`
57
	 *
58
	 * Matches this code:
59
	 *
60
	 *     preg_replace( "!$startDelim(.*?)$endDelim!", $replace, $subject );
61
	 *
62
	 * ..except that it's worst-case O(N) instead of O(N^2). Compared to delimiterReplace(), this
63
	 * implementation is fast but memory-hungry and inflexible. The memory requirements are such
64
	 * that I don't recommend using it on anything but guaranteed small chunks of text.
65
	 *
66
	 * @param string $startDelim
67
	 * @param string $endDelim
68
	 * @param string $replace
69
	 * @param string $subject
70
	 * @return string
71
	 */
72
	static function hungryDelimiterReplace( $startDelim, $endDelim, $replace, $subject ) {
73
		$segments = explode( $startDelim, $subject );
74
		$output = array_shift( $segments );
75
		foreach ( $segments as $s ) {
76
			$endDelimPos = strpos( $s, $endDelim );
77
			if ( $endDelimPos === false ) {
78
				$output .= $startDelim . $s;
79
			} else {
80
				$output .= $replace . substr( $s, $endDelimPos + strlen( $endDelim ) );
81
			}
82
		}
83
84
		return $output;
85
	}
86
87
	/**
88
	 * Perform an operation equivalent to `preg_replace_callback()`
89
	 *
90
	 * Matches this code:
91
	 *
92
	 *     preg_replace_callback( "!$startDelim(.*)$endDelim!s$flags", $callback, $subject );
93
	 *
94
	 * If the start delimiter ends with an initial substring of the end delimiter,
95
	 * e.g. in the case of C-style comments, the behavior differs from the model
96
	 * regex. In this implementation, the end must share no characters with the
97
	 * start, so e.g. `/*\/` is not considered to be both the start and end of a
98
	 * comment. `/*\/xy/*\/` is considered to be a single comment with contents `/xy/`.
99
	 *
100
	 * The implementation of delimiterReplaceCallback() is slower than hungryDelimiterReplace()
101
	 * but uses far less memory. The delimiters are literal strings, not regular expressions.
102
	 *
103
	 * @param string $startDelim Start delimiter
104
	 * @param string $endDelim End delimiter
105
	 * @param callable $callback Function to call on each match
106
	 * @param string $subject
107
	 * @param string $flags Regular expression flags
108
	 * @throws InvalidArgumentException
109
	 * @return string
110
	 */
111
	static function delimiterReplaceCallback( $startDelim, $endDelim, $callback,
112
		$subject, $flags = ''
113
	) {
114
		$inputPos = 0;
115
		$outputPos = 0;
116
		$output = '';
117
		$foundStart = false;
118
		$encStart = preg_quote( $startDelim, '!' );
119
		$encEnd = preg_quote( $endDelim, '!' );
120
		$strcmp = strpos( $flags, 'i' ) === false ? 'strcmp' : 'strcasecmp';
121
		$endLength = strlen( $endDelim );
122
		$m = [];
123
124
		while ( $inputPos < strlen( $subject ) &&
125
			preg_match( "!($encStart)|($encEnd)!S$flags", $subject, $m, PREG_OFFSET_CAPTURE, $inputPos )
126
		) {
127
			$tokenOffset = $m[0][1];
128
			if ( $m[1][0] != '' ) {
129
				if ( $foundStart &&
130
					$strcmp( $endDelim, substr( $subject, $tokenOffset, $endLength ) ) == 0
131
				) {
132
					# An end match is present at the same location
133
					$tokenType = 'end';
134
					$tokenLength = $endLength;
135
				} else {
136
					$tokenType = 'start';
137
					$tokenLength = strlen( $m[0][0] );
138
				}
139
			} elseif ( $m[2][0] != '' ) {
140
				$tokenType = 'end';
141
				$tokenLength = strlen( $m[0][0] );
142
			} else {
143
				throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__ );
144
			}
145
146
			if ( $tokenType == 'start' ) {
147
				# Only move the start position if we haven't already found a start
148
				# This means that START START END matches outer pair
149
				if ( !$foundStart ) {
150
					# Found start
151
					$inputPos = $tokenOffset + $tokenLength;
152
					# Write out the non-matching section
153
					$output .= substr( $subject, $outputPos, $tokenOffset - $outputPos );
154
					$outputPos = $tokenOffset;
155
					$contentPos = $inputPos;
156
					$foundStart = true;
157
				} else {
158
					# Move the input position past the *first character* of START,
159
					# to protect against missing END when it overlaps with START
160
					$inputPos = $tokenOffset + 1;
161
				}
162
			} elseif ( $tokenType == 'end' ) {
163
				if ( $foundStart ) {
164
					# Found match
165
					$output .= call_user_func( $callback, [
166
						substr( $subject, $outputPos, $tokenOffset + $tokenLength - $outputPos ),
167
						substr( $subject, $contentPos, $tokenOffset - $contentPos )
0 ignored issues
show
Bug introduced by
The variable $contentPos does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
168
					] );
169
					$foundStart = false;
170
				} else {
171
					# Non-matching end, write it out
172
					$output .= substr( $subject, $inputPos, $tokenOffset + $tokenLength - $outputPos );
173
				}
174
				$inputPos = $outputPos = $tokenOffset + $tokenLength;
175
			} else {
176
				throw new InvalidArgumentException( 'Invalid delimiter given to ' . __METHOD__ );
177
			}
178
		}
179
		if ( $outputPos < strlen( $subject ) ) {
180
			$output .= substr( $subject, $outputPos );
181
		}
182
183
		return $output;
184
	}
185
186
	/**
187
	 * Perform an operation equivalent to `preg_replace()` with flags.
188
	 *
189
	 * Matches this code:
190
	 *
191
	 *     preg_replace( "!$startDelim(.*)$endDelim!$flags", $replace, $subject );
192
	 *
193
	 * @param string $startDelim Start delimiter regular expression
194
	 * @param string $endDelim End delimiter regular expression
195
	 * @param string $replace Replacement string. May contain $1, which will be
196
	 *  replaced by the text between the delimiters
197
	 * @param string $subject String to search
198
	 * @param string $flags Regular expression flags
199
	 * @return string The string with the matches replaced
200
	 */
201
	static function delimiterReplace( $startDelim, $endDelim, $replace, $subject, $flags = '' ) {
202
		$replacer = new RegexlikeReplacer( $replace );
203
204
		return self::delimiterReplaceCallback( $startDelim, $endDelim,
205
			$replacer->cb(), $subject, $flags );
206
	}
207
208
	/**
209
	 * More or less "markup-safe" explode()
210
	 * Ignores any instances of the separator inside `<...>`
211
	 * @param string $separator
212
	 * @param string $text
213
	 * @return array
214
	 */
215
	static function explodeMarkup( $separator, $text ) {
216
		$placeholder = "\x00";
217
218
		// Remove placeholder instances
219
		$text = str_replace( $placeholder, '', $text );
220
221
		// Replace instances of the separator inside HTML-like tags with the placeholder
222
		$replacer = new DoubleReplacer( $separator, $placeholder );
223
		$cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
224
225
		// Explode, then put the replaced separators back in
226
		$items = explode( $separator, $cleaned );
227
		foreach ( $items as $i => $str ) {
228
			$items[$i] = str_replace( $placeholder, $separator, $str );
229
		}
230
231
		return $items;
232
	}
233
234
	/**
235
	 * More or less "markup-safe" str_replace()
236
	 * Ignores any instances of the separator inside `<...>`
237
	 * @param string $search
238
	 * @param string $replace
239
	 * @param string $text
240
	 * @return string
241
	 */
242
	static function replaceMarkup( $search, $replace, $text ) {
243
		$placeholder = "\x00";
244
245
		// Remove placeholder instances
246
		$text = str_replace( $placeholder, '', $text );
247
248
		// Replace instances of the separator inside HTML-like tags with the placeholder
249
		$replacer = new DoubleReplacer( $search, $placeholder );
250
		$cleaned = StringUtils::delimiterReplaceCallback( '<', '>', $replacer->cb(), $text );
251
252
		// Explode, then put the replaced separators back in
253
		$cleaned = str_replace( $search, $replace, $cleaned );
254
		$text = str_replace( $placeholder, $search, $cleaned );
255
256
		return $text;
257
	}
258
259
	/**
260
	 * Escape a string to make it suitable for inclusion in a preg_replace()
261
	 * replacement parameter.
262
	 *
263
	 * @param string $string
264
	 * @return string
265
	 */
266
	static function escapeRegexReplacement( $string ) {
267
		$string = str_replace( '\\', '\\\\', $string );
268
		$string = str_replace( '$', '\\$', $string );
269
		return $string;
270
	}
271
272
	/**
273
	 * Workalike for explode() with limited memory usage.
274
	 *
275
	 * @param string $separator
276
	 * @param string $subject
277
	 * @return ArrayIterator|ExplodeIterator
278
	 */
279
	static function explode( $separator, $subject ) {
280
		if ( substr_count( $subject, $separator ) > 1000 ) {
281
			return new ExplodeIterator( $separator, $subject );
282
		} else {
283
			return new ArrayIterator( explode( $separator, $subject ) );
284
		}
285
	}
286
}
287