Skip to content

Commit

Permalink
Don't crash if replacement cannot be represented as a string
Browse files Browse the repository at this point in the history
  • Loading branch information
GrahamCampbell committed Oct 4, 2023
1 parent e80bc1a commit e7df575
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/Illuminate/Support/Str.php
Original file line number Diff line number Diff line change
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,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 $fallback;
}
}

/**
* Replace the given value in the given string.
*
Expand Down
2 changes: 2 additions & 0 deletions tests/Support/SupportStrTest.php
Original file line number Diff line number Diff line change
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

0 comments on commit e7df575

Please sign in to comment.