Passed
Pull Request — master (#1)
by Guillaume
04:03
created

UnicodeString   F

Complexity

Total Complexity 104

Size/Duplication

Total Lines 327
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 164
dl 0
loc 327
rs 2
c 0
b 0
f 0
wmc 104

How to fix   Complexity   

Complex Class

Complex classes like UnicodeString often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UnicodeString, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symfony\Component\String;
13
14
use Symfony\Component\String\Exception\ExceptionInterface;
15
use Symfony\Component\String\Exception\InvalidArgumentException;
16
17
/**
18
 * Represents a string of Unicode grapheme clusters encoded as UTF-8.
19
 *
20
 * A letter followed by combining characters (accents typically) form what Unicode defines
21
 * as a grapheme cluster: a character as humans mean it in written texts. This class knows
22
 * about the concept and won't split a letter apart from its combining accents. It also
23
 * ensures all string comparisons happen on their canonically-composed representation,
24
 * ignoring e.g. the order in which accents are listed when a letter has many of them.
25
 *
26
 * @see https://unicode.org/reports/tr15/
27
 *
28
 * @author Nicolas Grekas <[email protected]>
29
 * @author Hugo Hamon <[email protected]>
30
 *
31
 * @throws ExceptionInterface
32
 */
33
class UnicodeString extends AbstractUnicodeString
34
{
35
    public function __construct(string $string = '')
36
    {
37
        $this->string = normalizer_is_normalized($string) ? $string : normalizer_normalize($string);
38
39
        if (false === $this->string) {
40
            throw new InvalidArgumentException('Invalid UTF-8 string.');
41
        }
42
    }
43
44
    public function append(string ...$suffix): AbstractString
45
    {
46
        $str = clone $this;
47
        $str->string = $this->string.(1 >= \count($suffix) ? ($suffix[0] ?? '') : implode('', $suffix));
48
        normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
49
50
        if (false === $str->string) {
51
            throw new InvalidArgumentException('Invalid UTF-8 string.');
52
        }
53
54
        return $str;
55
    }
56
57
    public function chunk(int $length = 1): array
58
    {
59
        if (1 > $length) {
60
            throw new InvalidArgumentException('The chunk length must be greater than zero.');
61
        }
62
63
        if ('' === $this->string) {
64
            return [];
65
        }
66
67
        $rx = '/(';
68
        while (65535 < $length) {
69
            $rx .= '\X{65535}';
70
            $length -= 65535;
71
        }
72
        $rx .= '\X{'.$length.'})/u';
73
74
        $str = clone $this;
75
        $chunks = [];
76
77
        foreach (preg_split($rx, $this->string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $chunk) {
78
            $str->string = $chunk;
79
            $chunks[] = clone $str;
80
        }
81
82
        return $chunks;
83
    }
84
85
    public function endsWith($suffix): bool
86
    {
87
        if ($suffix instanceof AbstractString) {
88
            $suffix = $suffix->string;
89
        } elseif (\is_array($suffix) || $suffix instanceof \Traversable) {
90
            return parent::endsWith($suffix);
91
        } else {
92
            $suffix = (string) $suffix;
93
        }
94
95
        $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
96
        normalizer_is_normalized($suffix, $form) ?: $suffix = normalizer_normalize($suffix, $form);
97
98
        if ('' === $suffix || false === $suffix) {
99
            return false;
100
        }
101
102
        if ($this->ignoreCase) {
103
            return 0 === mb_stripos(grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix)), $suffix, 0, 'UTF-8');
104
        }
105
106
        return $suffix === grapheme_extract($this->string, \strlen($suffix), GRAPHEME_EXTR_MAXBYTES, \strlen($this->string) - \strlen($suffix));
107
    }
108
109
    public function equalsTo($string): bool
110
    {
111
        if ($string instanceof AbstractString) {
112
            $string = $string->string;
113
        } elseif (\is_array($string) || $string instanceof \Traversable) {
114
            return parent::equalsTo($string);
115
        } else {
116
            $string = (string) $string;
117
        }
118
119
        $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
120
        normalizer_is_normalized($string, $form) ?: $string = normalizer_normalize($string, $form);
121
122
        if ('' !== $string && false !== $string && $this->ignoreCase) {
123
            return \strlen($string) === \strlen($this->string) && 0 === mb_stripos($this->string, $string, 0, 'UTF-8');
124
        }
125
126
        return $string === $this->string;
127
    }
128
129
    public function indexOf($needle, int $offset = 0): ?int
130
    {
131
        if ($needle instanceof AbstractString) {
132
            $needle = $needle->string;
133
        } elseif (\is_array($needle) || $needle instanceof \Traversable) {
134
            return parent::indexOf($needle, $offset);
135
        } else {
136
            $needle = (string) $needle;
137
        }
138
139
        $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
140
        normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
141
142
        if ('' === $needle || false === $needle) {
143
            return null;
144
        }
145
146
        $i = $this->ignoreCase ? grapheme_stripos($this->string, $needle, $offset) : grapheme_strpos($this->string, $needle, $offset);
147
148
        return false === $i ? null : $i;
149
    }
150
151
    public function indexOfLast($needle, int $offset = 0): ?int
152
    {
153
        if ($needle instanceof AbstractString) {
154
            $needle = $needle->string;
155
        } elseif (\is_array($needle) || $needle instanceof \Traversable) {
156
            return parent::indexOfLast($needle, $offset);
157
        } else {
158
            $needle = (string) $needle;
159
        }
160
161
        $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
162
        normalizer_is_normalized($needle, $form) ?: $needle = normalizer_normalize($needle, $form);
163
164
        if ('' === $needle || false === $needle) {
165
            return null;
166
        }
167
168
        $string = $this->string;
169
170
        if (0 > $offset) {
171
            // workaround https://bugs.php.net/74264
172
            if (0 > $offset += grapheme_strlen($needle)) {
173
                $string = grapheme_substr($string, 0, $offset);
174
            }
175
            $offset = 0;
176
        }
177
178
        $i = $this->ignoreCase ? grapheme_strripos($string, $needle, $offset) : grapheme_strrpos($string, $needle, $offset);
179
180
        return false === $i ? null : $i;
181
    }
182
183
    public function join(array $strings, string $lastGlue = null): AbstractString
184
    {
185
        $str = parent::join($strings, $lastGlue);
186
        normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
187
188
        return $str;
189
    }
190
191
    public function length(): int
192
    {
193
        return grapheme_strlen($this->string);
194
    }
195
196
    /**
197
     * @return static
198
     */
199
    public function normalize(int $form = self::NFC): parent
200
    {
201
        $str = clone $this;
202
203
        if (\in_array($form, [self::NFC, self::NFKC], true)) {
204
            normalizer_is_normalized($str->string, $form) ?: $str->string = normalizer_normalize($str->string, $form);
205
        } elseif (!\in_array($form, [self::NFD, self::NFKD], true)) {
206
            throw new InvalidArgumentException('Unsupported normalization form.');
207
        } elseif (!normalizer_is_normalized($str->string, $form)) {
208
            $str->string = normalizer_normalize($str->string, $form);
209
            $str->ignoreCase = null;
210
        }
211
212
        return $str;
213
    }
214
215
    public function prepend(string ...$prefix): AbstractString
216
    {
217
        $str = clone $this;
218
        $str->string = (1 >= \count($prefix) ? ($prefix[0] ?? '') : implode('', $prefix)).$this->string;
219
        normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
220
221
        if (false === $str->string) {
222
            throw new InvalidArgumentException('Invalid UTF-8 string.');
223
        }
224
225
        return $str;
226
    }
227
228
    public function replace(string $from, string $to): AbstractString
229
    {
230
        $str = clone $this;
231
        normalizer_is_normalized($from) ?: $from = normalizer_normalize($from);
232
233
        if ('' !== $from && false !== $from) {
234
            $tail = $str->string;
235
            $result = '';
236
            $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
237
238
            while (false !== $i = $indexOf($tail, $from)) {
239
                $slice = grapheme_substr($tail, 0, $i);
240
                $result .= $slice.$to;
241
                $tail = substr($tail, \strlen($slice) + \strlen($from));
242
            }
243
244
            $str->string = $result.$tail;
245
            normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
246
247
            if (false === $str->string) {
248
                throw new InvalidArgumentException('Invalid UTF-8 string.');
249
            }
250
        }
251
252
        return $str;
253
    }
254
255
    public function replaceMatches(string $fromRegexp, $to): AbstractString
256
    {
257
        $str = parent::replaceMatches($fromRegexp, $to);
258
        normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
259
260
        return $str;
261
    }
262
263
    public function slice(int $start = 0, int $length = null): AbstractString
264
    {
265
        $str = clone $this;
266
        $str->string = (string) grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX);
267
268
        return $str;
269
    }
270
271
    public function splice(string $replacement, int $start = 0, int $length = null): AbstractString
272
    {
273
        $str = clone $this;
274
        $start = $start ? \strlen(grapheme_substr($this->string, 0, $start)) : 0;
275
        $length = $length ? \strlen(grapheme_substr($this->string, $start, $length ?? \PHP_INT_MAX)) : $length;
276
        $str->string = substr_replace($this->string, $replacement, $start, $length ?? \PHP_INT_MAX);
277
        normalizer_is_normalized($str->string) ?: $str->string = normalizer_normalize($str->string);
278
279
        if (false === $str->string) {
280
            throw new InvalidArgumentException('Invalid UTF-8 string.');
281
        }
282
283
        return $str;
284
    }
285
286
    public function split(string $delimiter, int $limit = null, int $flags = null): array
287
    {
288
        if (1 > $limit = $limit ?? \PHP_INT_MAX) {
289
            throw new InvalidArgumentException('Split limit must be a positive integer.');
290
        }
291
292
        if ('' === $delimiter) {
293
            throw new InvalidArgumentException('Split delimiter is empty.');
294
        }
295
296
        if (null !== $flags) {
297
            return parent::split($delimiter.'u', $limit, $flags);
298
        }
299
300
        normalizer_is_normalized($delimiter) ?: $delimiter = normalizer_normalize($delimiter);
301
302
        if (false === $delimiter) {
303
            throw new InvalidArgumentException('Split delimiter is not a valid UTF-8 string.');
304
        }
305
306
        $str = clone $this;
307
        $tail = $this->string;
308
        $chunks = [];
309
        $indexOf = $this->ignoreCase ? 'grapheme_stripos' : 'grapheme_strpos';
310
311
        while (1 < $limit && false !== $i = $indexOf($tail, $delimiter)) {
312
            $str->string = grapheme_substr($tail, 0, $i);
313
            $chunks[] = clone $str;
314
            $tail = substr($tail, \strlen($str->string) + \strlen($delimiter));
315
            --$limit;
316
        }
317
318
        $str->string = $tail;
319
        $chunks[] = clone $str;
320
321
        return $chunks;
322
    }
323
324
    public function startsWith($prefix): bool
325
    {
326
        if ($prefix instanceof AbstractString) {
327
            $prefix = $prefix->string;
328
        } elseif (\is_array($prefix) || $prefix instanceof \Traversable) {
329
            return parent::startsWith($prefix);
330
        } else {
331
            $prefix = (string) $prefix;
332
        }
333
334
        $form = null === $this->ignoreCase ? \Normalizer::NFD : \Normalizer::NFC;
335
        normalizer_is_normalized($prefix, $form) ?: $prefix = normalizer_normalize($prefix, $form);
336
337
        if ('' === $prefix || false === $prefix) {
338
            return false;
339
        }
340
341
        if ($this->ignoreCase) {
342
            return 0 === mb_stripos(grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES), $prefix, 0, 'UTF-8');
343
        }
344
345
        return $prefix === grapheme_extract($this->string, \strlen($prefix), GRAPHEME_EXTR_MAXBYTES);
346
    }
347
348
    public function __wakeup()
349
    {
350
        normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
351
    }
352
353
    public function __clone()
354
    {
355
        if (null === $this->ignoreCase) {
356
            normalizer_is_normalized($this->string) ?: $this->string = normalizer_normalize($this->string);
357
        }
358
359
        $this->ignoreCase = false;
360
    }
361
}
362