bug #40203 [String] Check if function exists before declaring it (Nyholm)

This PR was squashed before being merged into the 5.2 branch.

Discussion
----------

[String] Check if function exists before declaring it

| Q             | A
| ------------- | ---
| Branch?       | 5.2
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        |

If you installed a command line tool like `psalm` with composer and then try to run it on a project that included the String component you will get an error like:

> Fatal error: Cannot redeclare Symfony\Component\String\u() (previously declared in /Workspace/symfony/src/Symfony/Component/String/Resources/functions.php:14) in /user/.composer/vendor/symfony/string/Resources/functions.php on line 14

That is because we are loading two installations of the string component.

Commits
-------

cc00e0eb78 [String] Check if function exists before declaring it
This commit is contained in:
Nicolas Grekas 2021-02-16 11:20:41 +01:00
commit 7dcf156242
2 changed files with 27 additions and 19 deletions

View File

@ -11,22 +11,28 @@
namespace Symfony\Component\String;
function u(?string $string = ''): UnicodeString
{
return new UnicodeString($string ?? '');
if (!\function_exists(u::class)) {
function u(?string $string = ''): UnicodeString
{
return new UnicodeString($string ?? '');
}
}
function b(?string $string = ''): ByteString
{
return new ByteString($string ?? '');
if (!\function_exists(b::class)) {
function b(?string $string = ''): ByteString
{
return new ByteString($string ?? '');
}
}
/**
* @return UnicodeString|ByteString
*/
function s(?string $string = ''): AbstractString
{
$string = $string ?? '';
if (!\function_exists(s::class)) {
/**
* @return UnicodeString|ByteString
*/
function s(?string $string = ''): AbstractString
{
$string = $string ?? '';
return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
return preg_match('//u', $string) ? new UnicodeString($string) : new ByteString($string);
}
}

View File

@ -11,10 +11,12 @@
namespace Symfony\Component\Translation;
/**
* @author Nate Wiebe <nate@northern.co>
*/
function t(string $message, array $parameters = [], string $domain = null): TranslatableMessage
{
return new TranslatableMessage($message, $parameters, $domain);
if (!\function_exists(t::class)) {
/**
* @author Nate Wiebe <nate@northern.co>
*/
function t(string $message, array $parameters = [], string $domain = null): TranslatableMessage
{
return new TranslatableMessage($message, $parameters, $domain);
}
}