Skip to content

Commit 34ff753

Browse files
committed
Refactor alias and title increment logic in StringHelper
1 parent e33cf9a commit 34ff753

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

Diff for: src/StringHelper.php

+17-21
Original file line numberDiff line numberDiff line change
@@ -56,29 +56,25 @@ public static function increment($string, $style = 'default', $n = 0)
5656
{
5757
$styleSpec = static::$incrementStyles[$style] ?? static::$incrementStyles['default'];
5858

59-
// Regular expression search and replace patterns.
60-
if (\is_array($styleSpec[0])) {
61-
$rxSearch = $styleSpec[0][0];
62-
$rxReplace = $styleSpec[0][1];
59+
// Regular expression search and replace patterns for both cases
60+
if ($style === 'default') {
61+
if (preg_match('#\((\d+)\)$#', $string, $matches)) {
62+
$n = empty($n) ? ($matches[1] + 1) : $n;
63+
$string = preg_replace('#\((\d+)\)$#', "($n)", $string);
64+
} else {
65+
$string .= ' (2)';
66+
}
6367
} else {
64-
$rxSearch = $rxReplace = $styleSpec[0];
65-
}
68+
$rxSearch = '#-(\d+)$#'; // Match the trailing number after a hyphen (e.g., "dog-2")
69+
$rxReplace = '-%d'; // Replace it with "-number"
6670

67-
// New and old (existing) sprintf formats.
68-
if (\is_array($styleSpec[1])) {
69-
$newFormat = $styleSpec[1][0];
70-
$oldFormat = $styleSpec[1][1];
71-
} else {
72-
$newFormat = $oldFormat = $styleSpec[1];
73-
}
74-
75-
// Check if we are incrementing an existing pattern, or appending a new one.
76-
if (preg_match($rxSearch, $string, $matches)) {
77-
$n = empty($n) ? ($matches[1] + 1) : $n;
78-
$string = preg_replace($rxReplace, sprintf($oldFormat, $n), $string);
79-
} else {
80-
$n = empty($n) ? 2 : $n;
81-
$string .= sprintf($newFormat, $n);
71+
if (preg_match($rxSearch, $string, $matches)) {
72+
$n = empty($n) ? ($matches[1] + 1) : $n;
73+
$string = preg_replace($rxReplace, sprintf($rxReplace, $n), $string);
74+
} else {
75+
$n = empty($n) ? 2 : $n;
76+
$string .= sprintf($rxReplace, $n);
77+
}
8278
}
8379

8480
return $string;

0 commit comments

Comments
 (0)