Skip to content

Commit

Permalink
add the ability to listen for multiple events via the $event property.
Browse files Browse the repository at this point in the history
  • Loading branch information
david-d-h committed Jan 4, 2024
1 parent eb43b39 commit 2c35983
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 25 deletions.
14 changes: 8 additions & 6 deletions src/Cached.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use ReflectionClass;

Expand Down Expand Up @@ -52,8 +53,9 @@ final public function handle($event = null): void
[$driver, $ident] = self::parseCacheString($this->store
?? throw new \Exception('The $store property in ['.static::class.'] must be overridden'),
);

Cache::driver($driver)->forever($ident,
/** @phpstan-ignore-next-line */
/** @phpstan-ignore-next-line */
$this->run($event),
);
}
Expand Down Expand Up @@ -111,20 +113,20 @@ public static function schedule($callback)
/**
* Get the event (if any) this cacher listens for.
*
* @return class-string<E>|null
* @return array<int, class-string<E>>
*/
final public static function getListenerEvent(): ?string
final public static function getListenerEvent(): array
{
$reflection = new ReflectionClass(static::class);

$concrete = $reflection->getProperty('event')->getDefaultValue();
$concrete = Arr::wrap($reflection->getProperty('event')->getDefaultValue());

/** @phpstan-ignore-next-line */
return $concrete ?? ($reflection
return $concrete ?: Arr::wrap(($reflection
->getMethod('run')
->getParameters()[0] ?? null)
?->getType()
?->getName();
?->getName());
}

/**
Expand Down
22 changes: 3 additions & 19 deletions src/PermanentCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,42 +11,26 @@ class PermanentCache
*/
protected array $cachers = [];

/**
* @var array<class-string, array<class-string<Cached>>>
*/
protected array $static = [];

/**
* @param array<int, class-string<Cached>> $cachers
* @return $this
*/
public function caches(array $cachers): self
{
foreach ($cachers as $cacher) {
$event = $cacher::getListenerEvent();
$events = $cacher::getListenerEvent();

if (is_null($event)) {
$static[] = $cacher;
$resolved[$cacher] = $events;

continue;
}
Event::listen($events, $cacher);

$resolved[$event][] = $cacher;

Event::listen($event, $cacher);
}

$this->cachers = array_merge($this->cachers, $resolved ?? []);
$this->static = array_merge($this->static, $static ?? []);

return $this;
}

public function staticCaches(): array
{
return $this->static;
}

public function configuredCaches(): array
{
return $this->cachers;
Expand Down

0 comments on commit 2c35983

Please sign in to comment.