Add quick function for getting and setting objects on item

This commit is contained in:
Tim
2025-08-28 23:01:36 +02:00
parent a5b6d2982b
commit 47f1a860b1

View File

@ -14,7 +14,7 @@ class Item
private array $data = []; private array $data = [];
public function __construct( public function __construct(
string|int|null $id = null string|int|null $id = null
) )
{ {
$id ??= sha1(microtime()); $id ??= sha1(microtime());
@ -39,7 +39,34 @@ class Item
// Data manipulation // Data manipulation
public function get(string $key, mixed $default = null): mixed 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 public function set(string $key, mixed $value): self
@ -49,6 +76,19 @@ class Item
return $this; 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 public function has(string $key): bool
{ {
return array_key_exists($key, $this->data); return array_key_exists($key, $this->data);