From 28a4065a6923d6b5ee37b6b51b07e72e1f41ecc4 Mon Sep 17 00:00:00 2001 From: Dave Mc Nicoll Date: Tue, 13 Jun 2023 15:33:21 -0400 Subject: [PATCH] - WIP on Object serialization --- src/ApcuCache.php | 18 ++++++++++++- src/ArrayCache.php | 2 +- src/Serialize/ObjectSerialize.php | 42 +++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 src/Serialize/ObjectSerialize.php diff --git a/src/ApcuCache.php b/src/ApcuCache.php index cded3ba..c160875 100644 --- a/src/ApcuCache.php +++ b/src/ApcuCache.php @@ -2,10 +2,13 @@ namespace Kash; +use Kash\Serialize\ObjectSerialize; +use Laravel\SerializableClosure\Contracts\Serializable; use Psr\SimpleCache\CacheException; use Psr\SimpleCache\CacheInterface; use Psr\SimpleCache\InvalidArgumentException; +use Ulmus\EntityCollection; use function apcu_fetch, apcu_store, apcu_delete, apcu_clear_cache, apcu_exists, apcu_enabled; class ApcuCache implements CacheInterface @@ -25,18 +28,25 @@ class ApcuCache implements CacheInterface } }; } - } public function get(string $key, mixed $default = null) : mixed { $value = apcu_fetch($this->fullKey($key), $status); + if ($value instanceof Serialize\ObjectSerialize) { + $value = $value->restore(); + } + return $status === true ? $value : $default; } public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null) : bool { + /*if ( is_object($value) && ! ( $value instanceof Serialize\ObjectSerialize )) { + $value = $this->serializeObject($value); + }*/ + return apcu_store($this->fullKey($key), $value, $this->handleTTL($ttl)); } @@ -102,4 +112,10 @@ class ApcuCache implements CacheInterface { return $this->invalidator . $this->namespace . static::DEFAULT_NS_SEPARATOR . $key; } + + protected function serializeObject(object $input) + { + $objSerialize = new ObjectSerialize(); + return $objSerialize->transform($input); + } } diff --git a/src/ArrayCache.php b/src/ArrayCache.php index 63702b5..9d5425e 100644 --- a/src/ArrayCache.php +++ b/src/ArrayCache.php @@ -17,7 +17,7 @@ class ArrayCache implements CacheInterface protected array $storageTTL = []; public function __construct( - protected CacheInvalidator $invalidator, + protected null|CacheInvalidator $invalidator, protected string $namespace, protected int $ttl = -1, ) { } diff --git a/src/Serialize/ObjectSerialize.php b/src/Serialize/ObjectSerialize.php new file mode 100644 index 0000000..45e997e --- /dev/null +++ b/src/Serialize/ObjectSerialize.php @@ -0,0 +1,42 @@ +objectType = $object::class; + + if ($object instanceof \Serializable) { + $this->objectData = $object->serialize(); + } + else { + $this->objectData = serialize($object); + } + + return $this; + } + + public function restore() : object + { + $cls = $this->objectType; + $obj = new $cls(); + + if ($object instanceof \Serializable) { + $obj->unserialize($this->objectData); + } + else { + # unserialize() + } + + return $obj; + } +} \ No newline at end of file