Add quick function for getting and setting objects on item
This commit is contained in:
@ -14,7 +14,7 @@ class Item
|
||||
private array $data = [];
|
||||
|
||||
public function __construct(
|
||||
string|int|null $id = null
|
||||
string|int|null $id = null
|
||||
)
|
||||
{
|
||||
$id ??= sha1(microtime());
|
||||
@ -39,7 +39,34 @@ class Item
|
||||
// Data manipulation
|
||||
public function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->has($key) ? $this->data[$key] : $default;
|
||||
if (!$this->has($key)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $this->data[$key];
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param class-string<T> $class
|
||||
* @return T
|
||||
*/
|
||||
public function getObject(string $class, mixed $default = null): mixed
|
||||
{
|
||||
$key = $this->getObjectKey($class);
|
||||
if (!$this->has($key)) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
if (!($this->data[$key] instanceof $class)) {
|
||||
throw new \RuntimeException(sprintf(
|
||||
"Item object '%s' is not an instance of '%s'",
|
||||
$this->data[$key]::class,
|
||||
$class
|
||||
));
|
||||
}
|
||||
|
||||
return $this->data[$key];
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value): self
|
||||
@ -49,6 +76,19 @@ class Item
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setObject(object $object): self
|
||||
{
|
||||
$this->data[$this->getObjectKey($object)] = $object;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
private function getObjectKey(object|string $object): string
|
||||
{
|
||||
$class = is_object($object) ? get_class($object) : $object;
|
||||
return 'obj_' . basename(str_replace('\\', '/', $class));
|
||||
}
|
||||
|
||||
public function has(string $key): bool
|
||||
{
|
||||
return array_key_exists($key, $this->data);
|
||||
|
Reference in New Issue
Block a user