Debian Codegraph @

vendor/jfcherng/php-mb-string/src/MbString.php

raw
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Jfcherng\Utility;
6
7 /**
8 * An internal UTF-32 multi-bytes string class.
9 *
10 * Because UTF-8 is varied-width, mb_*() is kinda O(n) when doing decoding.
11 * Using iconv() to make it UTF-32 and work with str*() can be possibly faster.
12 *
13 * UTF-32 is a fix-width encoding (1 char = 4 bytes).
14 * Note that the first 4 bytes in a UTF-32 string is the header (endian bytes).
15 *
16 * @author Jack Cherng <[email protected]>
17 */
18 class MbString extends \ArrayObject implements \Stringable
19 {
20 public const MBSTRING_CONVMETHOD_ICONV = 1;
21 public const MBSTRING_CONVMETHOD_MBSTRING = 2;
22
23 /**
24 * The way to convert text encoding.
25 *
26 * @var int
27 */
28 public static $convMethod;
29
30 /**
31 * UTF-32 string without endian bytes.
32 *
33 * @var string
34 */
35 protected $str;
36
37 /**
38 * The original encoding.
39 *
40 * @var string
41 */
42 protected $encoding;
43
44 /**
45 * The endian bytes for UTF-32.
46 *
47 * @var string
48 */
49 protected static $utf32Header;
50
51 /**
52 * The constructor.
53 *
54 * @param string $str the string
55 * @param string $encoding the encoding
56 */
57 public function __construct(string $str = '', string $encoding = 'UTF-8')
58 {
59 static::$convMethod ??= static::detectConvEncoding();
60 static::$utf32Header ??= static::getUtf32Header();
61
62 $this->encoding = $encoding;
63 $this->set($str);
64 }
65
66 /**
67 * Returns a string representation of the object.
68 *
69 * @return string string representation of the object
70 */
71 public function __toString(): string
72 {
73 return $this->get();
74 }
75
76 /**
77 * The string setter.
78 *
79 * @param string $str the string
80 */
81 public function set(string $str): self
82 {
83 $this->str = $this->inputConv($str);
84
85 return $this;
86 }
87
88 public function setAt(int $idx, string $char): self
89 {
90 $char = $this->inputConv($char);
91 if (\strlen($char) > 4) {
92 $char = substr($char, 0, 4);
93 }
94
95 $spacesPrepend = $idx - $this->strlen();
96 // set index (out of bound)
97 if ($spacesPrepend > 0) {
98 $this->str .= $this->inputConv(str_repeat(' ', $spacesPrepend)) . $char;
99 }
100 // set index (in bound)
101 else {
102 $this->str = substr_replace($this->str, $char, $idx << 2, 4);
103 }
104
105 return $this;
106 }
107
108 /**
109 * The string getter.
110 */
111 public function get(): string
112 {
113 return $this->outputConv($this->str);
114 }
115
116 /**
117 * The raw string getter.
118 *
119 * @return string the UTF-32-encoded raw string
120 */
121 public function getRaw(): string
122 {
123 return $this->str;
124 }
125
126 public function getAt(int $idx): string
127 {
128 return $this->outputConv(substr($this->str, $idx << 2, 4));
129 }
130
131 public function getAtRaw(int $idx): string
132 {
133 return substr($this->str, $idx << 2, 4);
134 }
135
136 public function toArray(): array
137 {
138 return self::strToChars($this->get());
139 }
140
141 public function toArraySplit(string $regex, int $limit = -1, $flags = 0): array
142 {
143 if ($this->str === '') {
144 return [];
145 }
146
147 return preg_split($regex, $this->get(), $limit, $flags);
148 }
149
150 public function toArrayRaw(): array
151 {
152 if ($this->str === '') {
153 return [];
154 }
155
156 return str_split($this->str, 4);
157 }
158
159 public static function strToChars(string $str): array
160 {
161 return preg_split('//uS', $str, -1, \PREG_SPLIT_NO_EMPTY) ?: [];
162 }
163
164 // /////////////////////////////////
165 // string manipulation functions //
166 // /////////////////////////////////
167
168 public function stripos(string $needle, int $offset = 0)
169 {
170 $needle = $this->inputConv($needle);
171 $pos = stripos($this->str, $needle, $offset << 2);
172
173 return \is_bool($pos) ? $pos : $pos >> 2;
174 }
175
176 public function strlen(): int
177 {
178 return \strlen($this->str) >> 2;
179 }
180
181 public function strpos(string $needle, int $offset = 0)
182 {
183 $needle = $this->inputConv($needle);
184 $pos = strpos($this->str, $needle, $offset << 2);
185
186 return \is_bool($pos) ? $pos : $pos >> 2;
187 }
188
189 public function substr(int $start = 0, ?int $length = null): string
190 {
191 return $this->outputConv(
192 isset($length)
193 ? substr($this->str, $start << 2, $length << 2)
194 : substr($this->str, $start << 2),
195 );
196 }
197
198 public function substr_replace(string $replacement, int $start = 0, ?int $length = null): string
199 {
200 $replacement = $this->inputConv($replacement);
201
202 return $this->outputConv(
203 isset($length)
204 ? substr_replace($this->str, $replacement, $start << 2, $length << 2)
205 : substr_replace($this->str, $replacement, $start << 2),
206 );
207 }
208
209 public function strtolower(): string
210 {
211 return strtolower($this->get());
212 }
213
214 public function strtoupper(): string
215 {
216 return strtoupper($this->get());
217 }
218
219 // //////////////////////////////
220 // non-manipulative functions //
221 // //////////////////////////////
222
223 public function has(string $needle): bool
224 {
225 $needle = $this->inputConv($needle);
226
227 return str_contains($this->str, $needle);
228 }
229
230 public function startsWith(string $needle): bool
231 {
232 $needle = $this->inputConv($needle);
233
234 return $needle === substr($this->str, 0, \strlen($needle));
235 }
236
237 public function endsWith(string $needle): bool
238 {
239 $needle = $this->inputConv($needle);
240 $length = \strlen($needle);
241
242 return $length === 0 ? true : $needle === substr($this->str, -$length);
243 }
244
245 // ///////////////////////////////////////////
246 // those functions will not return a value //
247 // ///////////////////////////////////////////
248
249 public function str_insert_i(string $insert, int $position): self
250 {
251 $insert = $this->inputConv($insert);
252 $this->str = substr_replace($this->str, $insert, $position << 2, 0);
253
254 return $this;
255 }
256
257 public function str_enclose_i(array $closures, int $start = 0, ?int $length = null): self
258 {
259 // ex: $closures = array('{', '}');
260 foreach ($closures as &$closure) {
261 $closure = $this->inputConv($closure);
262 }
263 unset($closure);
264
265 if (\count($closures) < 2) {
266 $closures[0] = $closures[1] = reset($closures);
267 }
268
269 if (isset($length)) {
270 $replacement = $closures[0] . substr($this->str, $start << 2, $length << 2) . $closures[1];
271 $this->str = substr_replace($this->str, $replacement, $start << 2, $length << 2);
272 } else {
273 $replacement = $closures[0] . substr($this->str, $start << 2) . $closures[1];
274 $this->str = substr_replace($this->str, $replacement, $start << 2);
275 }
276
277 return $this;
278 }
279
280 public function str_replace_i(string $search, string $replace): self
281 {
282 $search = $this->inputConv($search);
283 $replace = $this->inputConv($replace);
284 $this->str = str_replace($search, $replace, $this->str);
285
286 return $this;
287 }
288
289 public function substr_replace_i(string $replacement, int $start = 0, ?int $length = null): self
290 {
291 $replacement = $this->inputConv($replacement);
292 $this->str = (
293 isset($length)
294 ? substr_replace($this->str, $replacement, $start << 2, $length << 2)
295 : substr_replace($this->str, $replacement, $start << 2)
296 );
297
298 return $this;
299 }
300
301 // ///////////////
302 // ArrayObject //
303 // ///////////////
304
305 public function offsetSet(mixed $idx, mixed $char): void
306 {
307 $this->setAt($idx, $char);
308 }
309
310 public function offsetGet(mixed $idx): string
311 {
312 return $this->getAt($idx);
313 }
314
315 public function offsetExists(mixed $idx): bool
316 {
317 return \is_int($idx) ? $this->strlen() > $idx : false;
318 }
319
320 public function append(mixed $str): void
321 {
322 $this->str .= $this->inputConv($str);
323 }
324
325 public function count(): int
326 {
327 return $this->strlen();
328 }
329
330 // //////////////////
331 // misc functions //
332 // //////////////////
333
334 /**
335 * Gets the utf 32 header.
336 *
337 * @return string the UTF-32 header or empty string
338 */
339 protected static function getUtf32Header(): string
340 {
341 // just use any string to get the endian header, here we use "A"
342 $tmp = self::convEncoding('A', 'UTF-8', 'UTF-32');
343 // some distributions like "php alpine" docker image won't generate the header
344 return $tmp && \strlen($tmp) > 4 ? substr($tmp, 0, 4) : '';
345 }
346
347 protected static function detectConvEncoding(): int
348 {
349 if (\function_exists('iconv') && iconv('UTF-8', 'UTF-32', 'A') !== false) {
350 return static::MBSTRING_CONVMETHOD_ICONV;
351 }
352
353 if (\function_exists('mb_convert_encoding') && mb_convert_encoding('A', 'UTF-32', 'UTF-8') !== false) {
354 return static::MBSTRING_CONVMETHOD_MBSTRING;
355 }
356
357 throw new \RuntimeException('Either "iconv" or "mbstring" extension is required.');
358 }
359
360 protected static function convEncoding(string $str, string $from, string $to): string
361 {
362 if (static::$convMethod === static::MBSTRING_CONVMETHOD_ICONV) {
363 return iconv($from, $to, $str);
364 }
365
366 if (static::$convMethod === static::MBSTRING_CONVMETHOD_MBSTRING) {
367 return mb_convert_encoding($str, $to, $from);
368 }
369
370 throw new \RuntimeException('Unknown conversion method.');
371 }
372
373 /**
374 * Convert the output string to its original encoding.
375 *
376 * @param string $str The string
377 */
378 protected function outputConv(string $str): string
379 {
380 if ($str === '') {
381 return '';
382 }
383
384 return static::convEncoding(static::$utf32Header . $str, 'UTF-32', $this->encoding);
385 }
386
387 /**
388 * Convert the input string to UTF-32 without header.
389 *
390 * @param string $str The string
391 */
392 protected function inputConv(string $str): string
393 {
394 if ($str === '') {
395 return '';
396 }
397
398 return substr(static::convEncoding($str, $this->encoding, 'UTF-32'), \strlen(static::$utf32Header));
399 }
400 }