diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index ea39ba80be7b..edb9d711b385 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -16,6 +16,7 @@ use Ramsey\Uuid\UuidFactory; use Symfony\Component\Uid\Ulid; use Traversable; +use Throwable; use voku\helper\ASCII; class Str @@ -986,12 +987,26 @@ 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; } + /** + * @param mixed $value + * @param string $fallback + * @return string + */ + private static function toStringOr($value, $fallback) + { + try { + return (string) $value; + } catch (Throwable $e) { + return $search; + } + } + /** * Replace the given value in the given string. * diff --git a/tests/Support/SupportStrTest.php b/tests/Support/SupportStrTest.php index 73d1770fcb62..62a66737c4aa 100755 --- a/tests/Support/SupportStrTest.php +++ b/tests/Support/SupportStrTest.php @@ -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()