Skip to content

[String] Add the s() helper method #35625

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

Merged
merged 1 commit into from
Feb 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions src/Symfony/Component/String/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ CHANGELOG
* made `AbstractString::width()` follow POSIX.1-2001
* added `LazyString` which provides memoizing stringable objects
* The component is not marked as `@experimental` anymore.
* Added the `s()` helper method to get either an `UnicodeString` or `ByteString` instance,
depending of the input string UTF-8 compliancy.

5.0.0
-----
Expand Down
8 changes: 8 additions & 0 deletions src/Symfony/Component/String/Resources/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,11 @@ function b(string $string = ''): ByteString
{
return new ByteString($string);
}

/**
* @return UnicodeString|ByteString
*/
function s(string $string): AbstractString
{
return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
}
39 changes: 39 additions & 0 deletions src/Symfony/Component/String/Tests/FunctionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\String\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\String\AbstractString;
use Symfony\Component\String\ByteString;
use function Symfony\Component\String\s;
use Symfony\Component\String\UnicodeString;

final class FunctionsTest extends TestCase
{
/**
* @dataProvider provideS
*/
public function testS(AbstractString $expected, string $input)
{
$this->assertEquals($expected, s($input));
}

public function provideS()
{
return [
[new UnicodeString('foo'), 'foo'],
[new UnicodeString('अनुच्छेद'), 'अनुच्छेद'],
[new ByteString("b\x80ar"), "b\x80ar"],
[new ByteString("\xfe\xff"), "\xfe\xff"],
];
}
}