diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index 4f63e4073069..8699a1008a2d 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -2,6 +2,7 @@ namespace Illuminate\Support; +use ArrayAccess; use Closure; use Illuminate\Support\Facades\Date; use Illuminate\Support\Traits\Conditionable; @@ -10,7 +11,7 @@ use JsonSerializable; use Symfony\Component\VarDumper\VarDumper; -class Stringable implements JsonSerializable +class Stringable implements JsonSerializable, ArrayAccess { use Conditionable, Macroable, Tappable; @@ -1205,6 +1206,50 @@ public function jsonSerialize(): string return $this->__toString(); } + /** + * Determine if the given offset exists. + * + * @param mixed $offset + * @return bool + */ + public function offsetExists(mixed $offset): bool + { + return isset($this->value[$offset]); + } + + /** + * Get the value at the given offset. + * + * @param mixed $offset + * @return string + */ + public function offsetGet(mixed $offset): string + { + return $this->value[$offset]; + } + + /** + * Set the value at the given offset. + * + * @param mixed $offset + * @return void + */ + public function offsetSet(mixed $offset, mixed $value): void + { + $this->value[$offset] = $value; + } + + /** + * Unset the value at the given offset. + * + * @param mixed $offset + * @return void + */ + public function offsetUnset(mixed $offset): void + { + unset($this->value[$offset]); + } + /** * Proxy dynamic properties onto methods. * diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php index f547161f14d6..e88f64a08222 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -1179,4 +1179,13 @@ public function testToDateThrowsException() $this->stringable('not a date')->toDate(); } + + public function testArrayAccess() + { + $str = $this->stringable('my string'); + $this->assertSame('m', $str[0]); + $this->assertSame('t', $str[4]); + $this->assertTrue(isset($str[2])); + $this->assertFalse(isset($str[10])); + } }