From 47f1a860b154a4baf6b3fe1ae063880a01d0d642 Mon Sep 17 00:00:00 2001 From: Tim Date: Thu, 28 Aug 2025 23:01:36 +0200 Subject: [PATCH] Add quick function for getting and setting objects on item --- src/Pipeline/OptionsProcessor/Item.php | 46 ++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/src/Pipeline/OptionsProcessor/Item.php b/src/Pipeline/OptionsProcessor/Item.php index 71525b9..464420c 100644 --- a/src/Pipeline/OptionsProcessor/Item.php +++ b/src/Pipeline/OptionsProcessor/Item.php @@ -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 $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); @@ -85,4 +125,4 @@ class Item $this->parent = $parent; return $this; } -} \ No newline at end of file +}