Skip to content

Commit fee2b84

Browse files
authored
Refactor (#111)
1 parent 01be533 commit fee2b84

8 files changed

Lines changed: 105 additions & 62 deletions

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
- Enh #106: Using fully-qualified function calls to improve performance (@vjik)
99
- New #104: Add methods `StringHelper::trim()`, `StringHelper::ltrim()`, `StringHelper::rtrim()` (@olegbaturin)
1010
- Enh #83: Make minor refactoring with Rector help (@vjik)
11+
- Enh #111: Minor refactoring (@Tigrov)
1112

1213
## 2.1.2 July 27, 2023
1314

src/AbstractCombinedRegexp.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
use Exception;
88

9+
use function sprintf;
10+
911
/**
1012
* `CombinedRegexp` optimizes matching of multiple regular expressions.
1113
* Read more about the concept in

src/CombinedRegexp.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,12 @@
77
use Exception;
88
use InvalidArgumentException;
99

10+
use function array_values;
1011
use function count;
12+
use function implode;
13+
use function preg_match;
14+
use function str_repeat;
15+
use function strtr;
1116

1217
/**
1318
* `CombinedRegexp` optimizes matching of multiple regular expressions.
@@ -36,6 +41,7 @@ public function __construct(
3641
if (empty($patterns)) {
3742
throw new InvalidArgumentException('At least one pattern should be specified.');
3843
}
44+
3945
$this->patterns = array_values($patterns);
4046
$this->compiledPattern = $this->compilePatterns($this->patterns) . $this->flags;
4147
}
@@ -97,6 +103,7 @@ private function compilePatterns(array $patterns): string
97103
foreach ($patterns as $i => $pattern) {
98104
$quotedPatterns[] = $pattern . str_repeat('()', $i);
99105
}
106+
100107
$combinedRegexps = '(?|' . strtr(
101108
implode('|', $quotedPatterns),
102109
[self::REGEXP_DELIMITER => self::QUOTE_REPLACER]

src/Inflector.php

Lines changed: 33 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,18 @@
66

77
use Transliterator;
88

9+
use function addslashes;
10+
use function array_search;
911
use function extension_loaded;
12+
use function mb_strtolower;
13+
use function mb_substr;
14+
use function preg_match;
15+
use function preg_quote;
16+
use function preg_replace;
17+
use function str_replace;
18+
use function strtolower;
19+
use function strtr;
20+
use function trim;
1021

1122
/**
1223
* Inflector provides methods such as {@see pluralize()} or {@see slug()} that derive a new string based on
@@ -441,9 +452,11 @@ public function toPlural(string $input): string
441452
public function toSingular(string $input): string
442453
{
443454
$result = array_search($input, $this->specialRules, true);
455+
444456
if ($result !== false) {
445457
return $result;
446458
}
459+
447460
foreach ($this->singularizeRules as $rule => $replacement) {
448461
if (preg_match($rule, $input)) {
449462
return preg_replace($rule, $replacement, $input);
@@ -466,7 +479,9 @@ public function toSentence(string $input, bool $uppercaseAll = false): string
466479
{
467480
$input = $this->toHumanReadable($this->pascalCaseToId($input, '_'), $uppercaseAll);
468481

469-
return $uppercaseAll ? StringHelper::uppercaseFirstCharacterInEachWord($input) : StringHelper::uppercaseFirstCharacter($input);
482+
return $uppercaseAll
483+
? StringHelper::uppercaseFirstCharacterInEachWord($input)
484+
: StringHelper::uppercaseFirstCharacter($input);
470485
}
471486

472487
/**
@@ -502,6 +517,7 @@ public function pascalCaseToId(string $input, string $separator = '-', bool $str
502517
$regex = $strict
503518
? '/(?<=\p{L})(\p{Lu})/u'
504519
: '/(?<=\p{L})(?<!\p{Lu})(\p{Lu})/u';
520+
505521
$result = preg_replace($regex, addslashes($separator) . '\1', $input);
506522

507523
if ($separator !== '_') {
@@ -526,7 +542,11 @@ public function pascalCaseToId(string $input, string $separator = '-', bool $str
526542
*/
527543
public function toPascalCase(string $input): string
528544
{
529-
return str_replace(' ', '', StringHelper::uppercaseFirstCharacterInEachWord(preg_replace('/[^\pL\pN]+/u', ' ', $input)));
545+
return str_replace(
546+
' ',
547+
'',
548+
StringHelper::uppercaseFirstCharacterInEachWord(preg_replace('/[^\pL\pN]+/u', ' ', $input)),
549+
);
530550
}
531551

532552
/**
@@ -541,7 +561,9 @@ public function toHumanReadable(string $input, bool $uppercaseWords = false): st
541561
{
542562
$input = str_replace('_', ' ', preg_replace('/_id$/', '', $input));
543563

544-
return $uppercaseWords ? StringHelper::uppercaseFirstCharacterInEachWord($input) : StringHelper::uppercaseFirstCharacter($input);
564+
return $uppercaseWords
565+
? StringHelper::uppercaseFirstCharacterInEachWord($input)
566+
: StringHelper::uppercaseFirstCharacter($input);
545567
}
546568

547569
/**
@@ -559,7 +581,7 @@ public function toCamelCase(string $input): string
559581
{
560582
$input = $this->toPascalCase($input);
561583

562-
return mb_strtolower(mb_substr($input, 0, 1)) . mb_substr($input, 1, null);
584+
return mb_strtolower(mb_substr($input, 0, 1)) . mb_substr($input, 1);
563585
}
564586

565587
/**
@@ -620,10 +642,15 @@ public function tableToClass(string $tableName): string
620642
*/
621643
public function toSlug(string $input, string $replacement = '-', bool $lowercase = true): string
622644
{
645+
$quotedReplacement = preg_quote($replacement, '/');
623646
// replace all non words character
624-
$input = preg_replace('/[^a-zA-Z0-9]++/u', $replacement, $this->toTransliterated($input));
647+
$input = preg_replace('/[^a-zA-Z0-9]+/u', $replacement, $this->toTransliterated($input));
625648
// remove first and last replacements
626-
$input = preg_replace('/^(?:' . preg_quote($replacement, '/') . ')++|(?:' . preg_quote($replacement, '/') . ')++$/u' . ($lowercase ? 'i' : ''), '', $input);
649+
$input = preg_replace(
650+
"/^(?:$quotedReplacement)+|(?:$quotedReplacement)+$/u" . ($lowercase ? 'i' : ''),
651+
'',
652+
$input,
653+
);
627654

628655
return $lowercase ? strtolower($input) : $input;
629656
}

src/NumericHelper.php

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,15 @@
66

77
use InvalidArgumentException;
88

9+
use function filter_var;
10+
use function fmod;
911
use function gettype;
1012
use function in_array;
1113
use function is_bool;
14+
use function is_numeric;
15+
use function is_scalar;
16+
use function preg_replace;
17+
use function str_replace;
1218

1319
/**
1420
* Provides static methods to work with numeric strings.
@@ -34,6 +40,7 @@ public static function toOrdinal(mixed $value): string
3440
if (in_array($value % 100, [11, 12, 13], true)) {
3541
return $value . 'th';
3642
}
43+
3744
return match ($value % 10) {
3845
1 => $value . 'st',
3946
2 => $value . 'nd',
@@ -58,11 +65,11 @@ public static function normalize(mixed $value): string
5865
}
5966

6067
if (is_bool($value)) {
61-
$value = $value ? '1' : '0';
62-
} else {
63-
$value = (string)$value;
68+
return $value ? '1' : '0';
6469
}
65-
$value = str_replace([' ', ','], ['', '.'], $value);
70+
71+
$value = str_replace([' ', ','], ['', '.'], (string)$value);
72+
6673
return preg_replace('/\.(?=.*\.)/', '', $value);
6774
}
6875

src/StringHelper.php

Lines changed: 36 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,32 @@
66

77
use InvalidArgumentException;
88

9+
use function array_map;
910
use function array_slice;
11+
use function base64_decode;
12+
use function base64_encode;
13+
use function ceil;
1014
use function count;
11-
use function function_exists;
15+
use function implode;
1216
use function max;
1317
use function mb_strlen;
18+
use function mb_strrpos;
1419
use function mb_strtolower;
1520
use function mb_strtoupper;
1621
use function mb_substr;
1722
use function preg_match;
23+
use function preg_quote;
1824
use function preg_replace;
25+
use function preg_split;
26+
use function rtrim;
27+
use function sprintf;
1928
use function str_ends_with;
29+
use function str_repeat;
30+
use function str_replace;
2031
use function str_starts_with;
2132
use function strlen;
33+
use function strtr;
34+
use function trim;
2235

2336
/**
2437
* Provides static methods to work with strings.
@@ -36,7 +49,7 @@ final class StringHelper
3649
*
3750
* @return int The number of bytes in the given string.
3851
*/
39-
public static function byteLength(?string $input): int
52+
public static function byteLength(string|null $input): int
4053
{
4154
return mb_strlen((string)$input, '8bit');
4255
}
@@ -140,8 +153,13 @@ public static function substring(string $string, int $start, int $length = null,
140153
* If length is zero then this function will have the effect of inserting replacement into string at the given start offset.
141154
* @param string $encoding The encoding to use, defaults to "UTF-8".
142155
*/
143-
public static function replaceSubstring(string $string, string $replacement, int $start, ?int $length = null, string $encoding = 'UTF-8'): string
144-
{
156+
public static function replaceSubstring(
157+
string $string,
158+
string $replacement,
159+
int $start,
160+
int|null $length = null,
161+
string $encoding = 'UTF-8',
162+
): string {
145163
$stringLength = mb_strlen($string, $encoding);
146164

147165
if ($start < 0) {
@@ -160,7 +178,9 @@ public static function replaceSubstring(string $string, string $replacement, int
160178
$length = $stringLength - $start;
161179
}
162180

163-
return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $stringLength - $start - $length, $encoding);
181+
return mb_substr($string, 0, $start, $encoding)
182+
. $replacement
183+
. mb_substr($string, $start + $length, $stringLength - $start - $length, $encoding);
164184
}
165185

166186
/**
@@ -172,22 +192,9 @@ public static function replaceSubstring(string $string, string $replacement, int
172192
*
173193
* @return bool Returns true if first input starts with second input, false otherwise.
174194
*/
175-
public static function startsWith(string $input, ?string $with): bool
195+
public static function startsWith(string $input, string|null $with): bool
176196
{
177-
if ($with === null) {
178-
return true;
179-
}
180-
181-
if (function_exists('\str_starts_with')) {
182-
return str_starts_with($input, $with);
183-
}
184-
185-
$bytes = self::byteLength($with);
186-
if ($bytes === 0) {
187-
return true;
188-
}
189-
190-
return strncmp($input, $with, $bytes) === 0;
197+
return $with === null || str_starts_with($input, $with);
191198
}
192199

193200
/**
@@ -199,16 +206,15 @@ public static function startsWith(string $input, ?string $with): bool
199206
*
200207
* @return bool Returns true if first input starts with second input, false otherwise.
201208
*/
202-
public static function startsWithIgnoringCase(string $input, ?string $with): bool
209+
public static function startsWithIgnoringCase(string $input, string|null $with): bool
203210
{
204211
$bytes = self::byteLength($with);
212+
205213
if ($bytes === 0) {
206214
return true;
207215
}
208216

209-
/**
210-
* @psalm-suppress PossiblyNullArgument
211-
*/
217+
/** @psalm-suppress PossiblyNullArgument */
212218
return self::lowercase(self::substring($input, 0, $bytes, '8bit')) === self::lowercase($with);
213219
}
214220

@@ -221,27 +227,9 @@ public static function startsWithIgnoringCase(string $input, ?string $with): boo
221227
*
222228
* @return bool Returns true if first input ends with second input, false otherwise.
223229
*/
224-
public static function endsWith(string $input, ?string $with): bool
230+
public static function endsWith(string $input, string|null $with): bool
225231
{
226-
if ($with === null) {
227-
return true;
228-
}
229-
230-
if (function_exists('\str_ends_with')) {
231-
return str_ends_with($input, $with);
232-
}
233-
234-
$bytes = self::byteLength($with);
235-
if ($bytes === 0) {
236-
return true;
237-
}
238-
239-
// Warning check, see https://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
240-
if (self::byteLength($input) < $bytes) {
241-
return false;
242-
}
243-
244-
return substr_compare($input, $with, -$bytes, $bytes) === 0;
232+
return $with === null || str_ends_with($input, $with);
245233
}
246234

247235
/**
@@ -253,16 +241,15 @@ public static function endsWith(string $input, ?string $with): bool
253241
*
254242
* @return bool Returns true if first input ends with second input, false otherwise.
255243
*/
256-
public static function endsWithIgnoringCase(string $input, ?string $with): bool
244+
public static function endsWithIgnoringCase(string $input, string|null $with): bool
257245
{
258246
$bytes = self::byteLength($with);
247+
259248
if ($bytes === 0) {
260249
return true;
261250
}
262251

263-
/**
264-
* @psalm-suppress PossiblyNullArgument
265-
*/
252+
/** @psalm-suppress PossiblyNullArgument */
266253
return self::lowercase(mb_substr($input, -$bytes, mb_strlen($input, '8bit'), '8bit')) === self::lowercase($with);
267254
}
268255

@@ -433,9 +420,7 @@ public static function uppercaseFirstCharacterInEachWord(string $string, string
433420
$words = preg_split('/\s/u', $string, -1, PREG_SPLIT_NO_EMPTY);
434421

435422
$wordsWithUppercaseFirstCharacter = array_map(
436-
static function (string $word) use ($encoding) {
437-
return self::uppercaseFirstCharacter($word, $encoding);
438-
},
423+
static fn (string $word) => self::uppercaseFirstCharacter($word, $encoding),
439424
$words
440425
);
441426

src/WildcardPattern.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44

55
namespace Yiisoft\Strings;
66

7+
use function implode;
8+
use function preg_match;
9+
use function preg_quote;
10+
use function preg_replace;
11+
use function strtr;
12+
713
/**
814
* A wildcard pattern to match strings against.
915
*
@@ -106,7 +112,7 @@ public function ignoreCase(bool $flag = true): self
106112
public static function isDynamic(string $pattern): bool
107113
{
108114
$pattern = preg_replace('/\\\\./', '', $pattern);
109-
return (bool)preg_match('/[*{?\[]/', $pattern);
115+
return preg_match('/[*{?\[]/', $pattern) === 1;
110116
}
111117

112118
/**

tests/AbstractCombinedRegexpTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,5 +253,13 @@ public function testInvalidMatch(): void
253253
$regexp->getMatchingPattern($string);
254254
}
255255

256+
public function testGetFlags()
257+
{
258+
$patterns = ['/user/[\d+]', '/user/login'];
259+
260+
$this->assertSame('', $this->createCombinedRegexp($patterns)->getFlags());
261+
$this->assertSame('i', $this->createCombinedRegexp($patterns, 'i')->getFlags());
262+
}
263+
256264
abstract protected function createCombinedRegexp(array $patterns, string $flags = ''): AbstractCombinedRegexp;
257265
}

0 commit comments

Comments
 (0)