Skip to content

Commit

Permalink
[String] allow passing null to string functions
Browse files Browse the repository at this point in the history
  • Loading branch information
kbond authored and fabpot committed Sep 24, 2020
1 parent 0ebd63d commit 4dfc0b2
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
12 changes: 7 additions & 5 deletions Resources/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,22 @@

namespace Symfony\Component\String;

function u(string $string = ''): UnicodeString
function u(?string $string = ''): UnicodeString
{
return new UnicodeString($string);
return new UnicodeString($string ?? '');
}

function b(string $string = ''): ByteString
function b(?string $string = ''): ByteString
{
return new ByteString($string);
return new ByteString($string ?? '');
}

/**
* @return UnicodeString|ByteString
*/
function s(string $string): AbstractString
function s(?string $string = ''): AbstractString
{
$string = $string ?? '';

return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
}
46 changes: 43 additions & 3 deletions Tests/FunctionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,67 @@

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

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

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

/**
* @dataProvider provideUStrings
*/
public function testU(UnicodeString $expected, ?string $input)
{
$this->assertEquals($expected, u($input));
}

public function provideUStrings(): array
{
return [
[new UnicodeString(''), ''],
[new UnicodeString(''), null],
[new UnicodeString('foo'), 'foo'],
[new UnicodeString('अनुच्छेद'), 'अनुच्छेद'],
];
}

/**
* @dataProvider provideBStrings
*/
public function testB(ByteString $expected, ?string $input)
{
$this->assertEquals($expected, b($input));
}

public function provideBStrings(): array
{
return [
[new ByteString(''), ''],
[new ByteString(''), null],
[new ByteString("b\x80ar"), "b\x80ar"],
[new ByteString("\xfe\xff"), "\xfe\xff"],
];
}
}

0 comments on commit 4dfc0b2

Please sign in to comment.