[String] Add the s() helper method

This commit is contained in:
Thomas Calvet 2020-02-06 18:44:01 +01:00
parent 31da954f9b
commit 659cdf1871
3 changed files with 49 additions and 0 deletions

View File

@ -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
-----

View File

@ -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);
}

View File

@ -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"],
];
}
}