Skip to content

Commit

Permalink
[10.x] Don't crash if replacement cannot be represented as a string (#…
Browse files Browse the repository at this point in the history
…48530)

* Don't crash if replacement cannot be represented as a string

* Update Str.php

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
GrahamCampbell and taylorotwell committed Oct 6, 2023
1 parent 8f1a56d commit fcceb52
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
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

0 comments on commit fcceb52

Please sign in to comment.