Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add ArrayAccess to Stringable #46279

Merged
merged 3 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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.
*
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]));
}
}