8000 [String] Fix the `snake` method behavior with uppercase strings and special characters by antten · Pull Request #57788 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[String] Fix the snake method behavior with uppercase strings and special characters #57788

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
[String] improve snake method for byte string.
Better management of uppercase string and removal of special end-of-line characters.
  • Loading branch information
antten committed Jul 20, 2024
commit de925bbf554fe51c2ad4d9e44bea545e97b916ca
21 changes: 17 additions & 4 deletions src/Symfony/Component/String/ByteString.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,10 +366,23 @@ public function slice(int $start = 0, ?int $length = null): parent

public function snake(): parent
{
$str = $this->camel();
$str->string = strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], '\1_\2', $str->string));

return $str;
$str = clone $this;
$matches = [];

preg_match_all(
'/([a-z0-9]+(?=[A-Z]))|([A-Z][a-z0-9]+)|([A-Z]+(?=[A-Z][a-z]))|((?<=\w)?[a-zA-Z0-9]+(?=\w)?)/',
$str,
$matches
);

$strings = array_map(
function (string $matchedString) {
return mb_strtolower($matchedString);
},
$matches[0] ?? []
);

return new static(implode('_', $strings));
}

public function splice(string $replacement, int $start = 0, ?int $length = null): parent
Expand Down
12 changes: 7 additions & 5 deletions src/Symfony/Component/String/Tests/AbstractAsciiTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -1080,12 +1080,14 @@ public static function provideSnake()
['symfony_is_great', 'symfonyIsGREAT'],
['symfony_is_really_great', 'symfonyIsREALLYGreat'],
['symfony', 'SYMFONY'],
['symfonyisgreat', 'SYMFONY IS GREAT'],
['symfonyisgreat', 'SYMFONY_IS_GREAT'],
['symfony_is_great', 'SYMFONY IS GREAT'],
['symfony_is_great', 'SYMFONY_IS_GREAT'],
['symfony_is_great', 'symfony is great'],
['symfonyisgreat', 'SYMFONY IS GREAT'],
['symfonyisgreat', 'SYMFONY _ IS _ GREAT'],
['symfony_isgreat', 'Symfony IS GREAT!'],
['symfony_is_great', 'SYMFONY IS GREAT'],
['symfony_is_great', 'SYMFONY _ IS _ GREAT'],
['symfony_is_great', 'Symfony IS GREAT!'],
['123_customer_with_special_name', '123-customer,with/special#name'],
['this_value_should_be_false', 'This value should be false.'],
];
}

Expand Down
0