Skip to content

Commit b4e4d00

Browse files
committed
fix: str to camel convert error
1 parent afbd37f commit b4e4d00

File tree

2 files changed

+35
-21
lines changed

2 files changed

+35
-21
lines changed

src/Str/Traits/StringCaseHelperTrait.php

+17-21
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,23 @@ public static function toCamel(string $str, bool $upperFirst = false): string
187187
return self::toCamelCase($str, $upperFirst);
188188
}
189189

190+
/**
191+
* Translates a string with `\s_-` into camel case (e.g. first_name -> firstName)
192+
*
193+
* @param string $str
194+
* @param bool $upperFirst
195+
*
196+
* @return mixed
197+
*/
198+
public static function toCamelCase(string $str, bool $upperFirst = false): string
199+
{
200+
if ($upperFirst) {
201+
$str = self::ucfirst($str);
202+
}
203+
204+
return preg_replace_callback('/[\s_-]+([a-z])/', static fn($c) => strtoupper($c[1]), $str);
205+
}
206+
190207
/**
191208
* string to camel case
192209
*
@@ -211,27 +228,6 @@ public static function camelCase(string $name, bool $upFirst = false, string $se
211228
return $upFirst ? ucfirst($name) : lcfirst($name);
212229
}
213230

214-
/**
215-
* Translates a string with underscores into camel case (e.g. first_name -> firstName)
216-
*
217-
* @param string $str
218-
* @param bool $upperFirst
219-
*
220-
* @return mixed
221-
*/
222-
public static function toCamelCase(string $str, bool $upperFirst = false): string
223-
{
224-
$str = self::toLower($str);
225-
226-
if ($upperFirst) {
227-
$str = self::ucfirst($str);
228-
}
229-
230-
return preg_replace_callback('/[_-]+([a-z])/', static function ($c) {
231-
return strtoupper($c[1]);
232-
}, $str);
233-
}
234-
235231
/**
236232
* @param string $str
237233
* @param string $sep

test/Str/StringHelperTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,23 @@ public function testStrpos(): void
147147
self::assertFalse(Str::notContains('abc', 'b'));
148148
}
149149

150+
public function testStrCase_toCamel(): void
151+
{
152+
$tests = [
153+
['voicePlayTimes', 'voicePlayTimes', 'VoicePlayTimes'],
154+
['fieldName', 'fieldName', 'FieldName'],
155+
['the_fieldName', 'theFieldName', 'TheFieldName'],
156+
['the_field_name', 'theFieldName', 'TheFieldName'],
157+
['the-field-name', 'theFieldName', 'TheFieldName'],
158+
['the field name', 'theFieldName', 'TheFieldName'],
159+
];
160+
161+
foreach ($tests as [$case, $want, $want1]) {
162+
$this->assertEquals(Str::toCamel($case), $want);
163+
$this->assertEquals(Str::toCamel($case, true), $want1);
164+
}
165+
}
166+
150167
public function testToNoEmptyArray(): void
151168
{
152169
$tests = [
@@ -240,4 +257,5 @@ public function testSplitTypedList(): void
240257
}
241258
}
242259

260+
243261
}

0 commit comments

Comments
 (0)