Skip to content

Commit e662cc4

Browse files
feature #35625 [String] Add the s() helper method (fancyweb)
This PR was merged into the 5.1-dev branch. Discussion ---------- [String] Add the s() helper method | Q | A | ------------- | --- | Branch? | master | Bug fix? | no | New feature? | yes | Deprecations? | no | Tickets | #35578 (comment) | License | MIT | Doc PR | - This method will be useful in our code base, and to anyone that doesn't really understand the differences between UnicodeString and ByteString. Commits ------- 659cdf1 [String] Add the s() helper method
2 parents 31da954 + 659cdf1 commit e662cc4

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/Symfony/Component/String/CHANGELOG.md

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ CHANGELOG
88
* made `AbstractString::width()` follow POSIX.1-2001
99
* added `LazyString` which provides memoizing stringable objects
1010
* The component is not marked as `@experimental` anymore.
11+
* Added the `s()` helper method to get either an `UnicodeString` or `ByteString` instance,
12+
depending of the input string UTF-8 compliancy.
1113

1214
5.0.0
1315
-----

src/Symfony/Component/String/Resources/functions.php

+8
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,11 @@ function b(string $string = ''): ByteString
2020
{
2121
return new ByteString($string);
2222
}
23+
24+
/**
25+
* @return UnicodeString|ByteString
26+
*/
27+
function s(string $string): AbstractString
28+
{
29+
return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\String\Tests;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\String\AbstractString;
16+
use Symfony\Component\String\ByteString;
17+
use function Symfony\Component\String\s;
18+
use Symfony\Component\String\UnicodeString;
19+
20+
final class FunctionsTest extends TestCase
21+
{
22+
/**
23+
* @dataProvider provideS
24+
*/
25+
public function testS(AbstractString $expected, string $input)
26+
{
27+
$this->assertEquals($expected, s($input));
28+
}
29+
30+
public function provideS()
31+
{
32+
return [
33+
[new UnicodeString('foo'), 'foo'],
34+
[new UnicodeString('अनुच्छेद'), 'अनुच्छेद'],
35+
[new ByteString("b\x80ar"), "b\x80ar"],
36+
[new ByteString("\xfe\xff"), "\xfe\xff"],
37+
];
38+
}
39+
}

0 commit comments

Comments
 (0)