Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Don't crash if replacement cannot be represented as a string #48530

Merged
merged 2 commits into from Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/Illuminate/Support/Str.php
Expand Up @@ -15,6 +15,7 @@
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use Symfony\Component\Uid\Ulid;
use Throwable;
use Traversable;
use voku\helper\ASCII;

Expand Down Expand Up @@ -986,12 +987,28 @@ public static function replaceArray($search, $replace, $subject)
$result = array_shift($segments);

foreach ($segments as $segment) {
$result .= (array_shift($replace) ?? $search).$segment;
$result .= self::toStringOr(array_shift($replace) ?? $search, $search).$segment;
}

return $result;
}

/**
* Convert the given value to a string or return the given fallback on failure.
*
* @param mixed $value
* @param string $fallback
* @return string
*/
private static function toStringOr($value, $fallback)
{
try {
return (string) $value;
} catch (Throwable $e) {
return $fallback;
}
}

/**
* Replace the given value in the given string.
*
Expand Down
2 changes: 2 additions & 0 deletions tests/Support/SupportStrTest.php
Expand Up @@ -594,6 +594,8 @@ public function testReplaceArray()
// Test for associative array support
$this->assertSame('foo/bar', Str::replaceArray('?', [1 => 'foo', 2 => 'bar'], '?/?'));
$this->assertSame('foo/bar', Str::replaceArray('?', ['x' => 'foo', 'y' => 'bar'], '?/?'));
// Test does not crash on bad input
$this->assertSame('?', Str::replaceArray('?', [(object) ['foo' => 'bar']], '?'));
}

public function testReplaceFirst()
Expand Down