Skip to content

Commit

Permalink
feature #35625 [String] Add the s() helper method (fancyweb)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
nicolas-grekas committed Feb 7, 2020
2 parents 31da954 + 659cdf1 commit e662cc4
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Symfony/Component/String/CHANGELOG.md
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
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
@@ -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"],
];
}
}

0 comments on commit e662cc4

Please sign in to comment.