Skip to content

Commit

Permalink
[10.x] Add ArrayAccess to Stringable (#46279)
Browse files Browse the repository at this point in the history
* Add ArrayAccess to Stringable.

* Fix typos and mistakes.

* formatting

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
mathieutu and taylorotwell authored Mar 1, 2023
1 parent 972e4db commit 1dff6a3
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
47 changes: 46 additions & 1 deletion src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Support;

use ArrayAccess;
use Closure;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Traits\Conditionable;
Expand All @@ -10,7 +11,7 @@
use JsonSerializable;
use Symfony\Component\VarDumper\VarDumper;

class Stringable implements JsonSerializable
class Stringable implements JsonSerializable, ArrayAccess
{
use Conditionable, Macroable, Tappable;

Expand Down Expand Up @@ -1216,6 +1217,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.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]));
}
}

0 comments on commit 1dff6a3

Please sign in to comment.