Skip to content

Commit 1dff6a3

Browse files
[10.x] Add ArrayAccess to Stringable (#46279)
* Add ArrayAccess to Stringable. * Fix typos and mistakes. * formatting --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 972e4db commit 1dff6a3

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

src/Illuminate/Support/Stringable.php

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Support;
44

5+
use ArrayAccess;
56
use Closure;
67
use Illuminate\Support\Facades\Date;
78
use Illuminate\Support\Traits\Conditionable;
@@ -10,7 +11,7 @@
1011
use JsonSerializable;
1112
use Symfony\Component\VarDumper\VarDumper;
1213

13-
class Stringable implements JsonSerializable
14+
class Stringable implements JsonSerializable, ArrayAccess
1415
{
1516
use Conditionable, Macroable, Tappable;
1617

@@ -1216,6 +1217,50 @@ public function jsonSerialize(): string
12161217
return $this->__toString();
12171218
}
12181219

1220+
/**
1221+
* Determine if the given offset exists.
1222+
*
1223+
* @param mixed $offset
1224+
* @return bool
1225+
*/
1226+
public function offsetExists(mixed $offset): bool
1227+
{
1228+
return isset($this->value[$offset]);
1229+
}
1230+
1231+
/**
1232+
* Get the value at the given offset.
1233+
*
1234+
* @param mixed $offset
1235+
* @return string
1236+
*/
1237+
public function offsetGet(mixed $offset): string
1238+
{
1239+
return $this->value[$offset];
1240+
}
1241+
1242+
/**
1243+
* Set the value at the given offset.
1244+
*
1245+
* @param mixed $offset
1246+
* @return void
1247+
*/
1248+
public function offsetSet(mixed $offset, mixed $value): void
1249+
{
1250+
$this->value[$offset] = $value;
1251+
}
1252+
1253+
/**
1254+
* Unset the value at the given offset.
1255+
*
1256+
* @param mixed $offset
1257+
* @return void
1258+
*/
1259+
public function offsetUnset(mixed $offset): void
1260+
{
1261+
unset($this->value[$offset]);
1262+
}
1263+
12191264
/**
12201265
* Proxy dynamic properties onto methods.
12211266
*

tests/Support/SupportStringableTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1179,4 +1179,13 @@ public function testToDateThrowsException()
11791179

11801180
$this->stringable('not a date')->toDate();
11811181
}
1182+
1183+
public function testArrayAccess()
1184+
{
1185+
$str = $this->stringable('my string');
1186+
$this->assertSame('m', $str[0]);
1187+
$this->assertSame('t', $str[4]);
1188+
$this->assertTrue(isset($str[2]));
1189+
$this->assertFalse(isset($str[10]));
1190+
}
11821191
}

0 commit comments

Comments
 (0)