diff --git a/config/permanent-cache.php b/config/permanent-cache.php index a22cfbd..231ec0c 100644 --- a/config/permanent-cache.php +++ b/config/permanent-cache.php @@ -1,5 +1,5 @@ env('PERMANENT_CACHE_STORE', 'file'), + 'default_store' => env('DEFAULT_PERMANENT_CACHE_STORE', 'file'), ]; diff --git a/src/Cached.php b/src/Cached.php new file mode 100644 index 0000000..7bcc0a0 --- /dev/null +++ b/src/Cached.php @@ -0,0 +1,93 @@ +|null + */ + protected $event = null; + + /** + * @param T $event + * @return void + */ + public final function handle($event = null): void + { + [$driver, $ident] = self::parseCacheString($this->cache); + + Cache::driver($driver)->forever($ident, + $this->run($event), + ); + } + + public final static function get() + { + $cache = (new ReflectionClass(static::class)) + ->getProperty('cache') + ->getDefaultValue(); + + [$driver, $ident] = self::parseCacheString($cache); + + return Cache::driver($driver)->get($ident); + } + + /** + * @return class-string + * + * @throws ReflectionException + */ + public final static function getListenerEvent(): string + { + $reflection = new ReflectionClass(static::class); + + $concrete = $reflection->getProperty('event')->getDefaultValue(); + + return $concrete ?? ($reflection + ->getMethod('run') + ->getParameters() + [0] ?? null) + ?->getType() + ?->getName() + ?? UpdatingPermanentCacheEvent::class; + } + + /** + * @param string $cache + * + * @return array{string, string} + */ + private static function parseCacheString(string $cache): array + { + [$driver, $ident] = explode(':', $cache) + [1 => null]; + + if (is_null($ident)) { + [$driver, $ident] = [config('permanent-cache.default_store'), $driver]; + } + + return [$driver, $ident]; + } +} diff --git a/src/PermanentCache.php b/src/PermanentCache.php index 48b8156..b65d981 100755 --- a/src/PermanentCache.php +++ b/src/PermanentCache.php @@ -10,11 +10,15 @@ class PermanentCache { protected array $cachers = []; + /** + * @param array> $cachers + * + * @return $this + */ public function caches(array $cachers): self { foreach ($cachers as $cacher) { - $event = $this->resolveEventType($cacher) - ?: UpdatingPermanentCacheEvent::class; + $event = $cacher::getListenerEvent(); $resolved[$event][] = $cacher; @@ -26,26 +30,6 @@ public function caches(array $cachers): self return $this; } - /** - * @return class-string|false - * - * @throws \ReflectionException - * @throws \Exception - */ - protected function resolveEventType(string $class): string|false - { - if (! method_exists($class, 'run')) { - throw new \Exception('Every cacher needs a run method.'); - } - - return ((new \ReflectionClass($class)) - ->getMethod('run') - ->getParameters()[0] ?? null) - ?->getType() - ?->getName() - ?? false; - } - /** * @return Collection> */