Last active
November 4, 2024 19:11
-
-
Save nyamsprod/c8072b382074a474a22bc94e4a5dd3ab to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @implements ArrayAccess<BackedEnum|array-key, mixed> | |
*/ | |
class Foobar implements ArrayAccess | |
{ | |
/** | |
* @param array<array-key, mixed> $members | |
*/ | |
public function __construct(private array $members) {} | |
private function filterKey(BackedEnum|string|int $key): string|int | |
{ | |
return match (true) { | |
$key instanceof BackedEnum => $key->value, | |
default => $key, | |
}; | |
} | |
/** | |
* @param BackedEnum|array-key $offset | |
*/ | |
public function offsetExists(mixed $offset): bool | |
{ | |
return array_key_exists($this->filterKey($offset), $this->members); | |
} | |
/** | |
* @param BackedEnum|array-key $offset | |
*/ | |
public function offsetGet(mixed $offset): mixed | |
{ | |
return $this->members[$this->filterKey($offset)] ?? throw new OutOfBoundsException('Member not found'); | |
} | |
/** | |
* @param BackedEnum|array-key $offset | |
*/ | |
public function offsetUnset(mixed $offset): void | |
{ | |
unset($this->members[$this->filterKey($offset)]); | |
} | |
/** | |
* @param BackedEnum|array-key|null $offset | |
*/ | |
public function offsetSet(mixed $offset, mixed $value): void | |
{ | |
if (null !== $offset) { | |
$this->members[$this->filterKey($offset)] = $value; | |
return; | |
} | |
$this->members[] = $value; | |
} | |
} | |
enum Attr: string | |
{ | |
case Foo = 'foo'; | |
case Bar = 'bar'; | |
case Toto = 'toto'; | |
} | |
$obj = new Foobar(['foo' => 1, 'bar' => 2, 'baz' => 3]); | |
$obj[Attr::Toto] = 'tata'; | |
var_dump( | |
$obj[Attr::Foo], | |
isset($obj[Attr::Bar]) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment