diff --git a/src/Illuminate/Support/Str.php b/src/Illuminate/Support/Str.php index ea39ba80be7b..e9278aaa2d5b 100644 --- a/src/Illuminate/Support/Str.php +++ b/src/Illuminate/Support/Str.php @@ -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; @@ -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. * 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()