Skip to content

Commit

Permalink
Merge pull request #12 from vormkracht10/tests
Browse files Browse the repository at this point in the history
Optimize code
  • Loading branch information
markvaneijk authored Apr 27, 2024
2 parents d6e2b94 + 87bb683 commit 434cb09
Show file tree
Hide file tree
Showing 4 changed files with 117 additions and 29 deletions.
4 changes: 2 additions & 2 deletions src/CachedComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
use Illuminate\View\Component;

/**
* @method string render()
* @method mixed get(array $parameters = [], bool $update = false)
*/
abstract class CachedComponent extends Component
{
use CachesValue;

/** {@inheritdoc} */
public function resolveView(): \Illuminate\Contracts\View\View|HtmlString|\Illuminate\Contracts\Support\Htmlable|\Closure|string
public function resolveView()
{
if (
$this->isUpdating ||
Expand Down
56 changes: 36 additions & 20 deletions src/CachesValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Bus\Queueable;
use Illuminate\Console\Scheduling\CallbackEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\PendingDispatch;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Cache;
Expand Down Expand Up @@ -44,18 +45,27 @@ trait CachesValue
*/
protected $expression = null;

/** @var array<string, mixed> */
/**
* The parameters this cache should be stored with.
*
* @var array<string, mixed>
*/
protected $parameters = [];

private bool $isUpdating = false;
/**
* Indicates whether this cache is currently updating or not.
*
* @var bool
*/
private $isUpdating = false;

/**
* Update the cached value, this method expects an event if
* the cacher is not static.
*
* @internal You shouldn't call this yourself.
* @internal You shouldn't call this yourself, use the `CachesValue::update` method instead.
*/
final public function handle($event = null): mixed
final public function handle($event = null): void
{
$this->isUpdating = true;

Expand All @@ -68,16 +78,14 @@ final public function handle($event = null): mixed
: $this->run($event);

if (is_null($value)) {
return null;
return;
}

Cache::driver($driver)->forever($cacheKey, $value);

PermanentCacheUpdated::dispatch($this);

$this->isUpdating = false;

return $value;
}

public function getParameters()
Expand Down Expand Up @@ -113,20 +121,17 @@ public function shouldBeUpdating(): bool
/**
* Manually force a static cache to update.
*/
final public static function update($parameters = []): mixed
final public static function update($parameters = []): ?PendingDispatch
{
$instance = app()->make(static::class, $parameters);

if (
app()->runningInConsole() &&
is_subclass_of(static::class, ShouldQueue::class)
) {
dispatch($instance);
if (! is_subclass_of(static::class, ShouldQueue::class)) {
$instance->handle();

return null;
}

return $instance->handle();
return dispatch($instance);
}

/**
Expand All @@ -147,16 +152,27 @@ final public static function get($default = null, bool $update = false): mixed

$cache = Cache::driver($driver);

if (
$update ||
! $cache->has($cacheKey)
) {
return static::update($parameters ?? []);
if ($update && ! $cache->has($cacheKey)) {
static::update($parameters ?? [])->onConnection('sync');
}

return $cache->get($cacheKey, $default);
}

/**
* Force an update of the cache and return the updated value.
*
* @return V|mixed
*/
final public static function updateAndGet($parameters = []): mixed
{
[$driver, $cacheKey] = self::store($parameters);

static::update($parameters)->onConnection('sync');

return Cache::driver($driver)->get($cacheKey);
}

/**
* Get the cached value this cacher provides.
*
Expand Down Expand Up @@ -237,7 +253,7 @@ private static function parseCacheString($class, ?string $store, ?array $paramet
}

$cacheDriver ??= config('cache.default');
$cacheKey ??= preg_replace('/[^A-Za-z0-9]+/', '_', strtolower(snake_case($class)));
$cacheKey ??= preg_replace('/[^A-Za-z0-9]+/', '_', strtolower(\Str::snake($class)));

if ($parameters) {
$cacheKey .= ':'.http_build_query($parameters);
Expand Down
17 changes: 10 additions & 7 deletions src/PermanentCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@

class PermanentCache
{
public function __construct(protected SplObjectStorage $cachers, protected Application $app)
{
public function __construct(
protected SplObjectStorage $cachers,
protected Application $app,
) {
//
}

/**
Expand All @@ -33,18 +36,18 @@ public function caches($registeredCaches): self
$cacher = array_key_first($parameters);
$parameters = array_shift($parameters);
} else {
$cacher = array_first($parameters);
$cacher = \Arr::first($parameters);
$parameters = [];
}
}

$cacher = $this->app->make($cacher, $parameters);
$cacherInstance = $this->app->make($cacher, $parameters);

if ([] !== $events = $cacher::getListenerEvents()) {
Event::listen($events, fn () => $cacher->update($parameters));
if ([] !== $events = $cacherInstance->getListenerEvents()) {
Event::listen($events, fn ($event) => $cacherInstance->handle($event));
}

$this->cachers[$cacher] = $events;
$this->cachers[$cacherInstance] = $events;
}
}

Expand Down
69 changes: 69 additions & 0 deletions tests/Unit/ReactiveCacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Vormkracht10\PermanentCache\Cached;
use Vormkracht10\PermanentCache\Events\PermanentCacheUpdated;
use Vormkracht10\PermanentCache\Events\PermanentCacheUpdating;
use Vormkracht10\PermanentCache\Facades\PermanentCache;

beforeEach(function () {
Cache::driver('array')->clear();
(fn () => $this->cachers = new \SplObjectStorage)->call(app(\Vormkracht10\PermanentCache\PermanentCache::class));
});

class TestEvent
{
}

class TestCache extends Cached
{
protected $store = 'array:test';

public function run(TestEvent $_): mixed
{
return 'it works!';
}
}

test('caches (listeners) get registered properly when using the PermanentCache facade', function () {
$events = Event::fake([TestEvent::class]);

PermanentCache::caches([TestCache::class]);

$caches = PermanentCache::configuredCaches();

expect($caches)
->count()->toBe(1)
->current()->toBeInstanceOf(TestCache::class)
->and($events)->hasListeners(TestEvent::class);
});

test('a cache will get updated when an event it\'s listening to gets fired', function () {
global $pass;
$pass = false;

class T extends Cached
{
public function run(TestEvent $_)
{
global $pass;
$pass = true;
}
}

Event::fakeExcept(TestEvent::class);
PermanentCache::caches(T::class);
event(new TestEvent);

expect($pass)->toBeTrue();
unset($pass);
});

test('a cache will dispatch the updating and updated events when it gets invoked', function () {
Event::fakeExcept(TestEvent::class);
Permanentcache::caches(TestCache::class);
event(new TestEvent);
Event::assertDispatchedTimes(PermanentCacheUpdating::class, times: 1);
Event::assertDispatchedTimes(PermanentCacheUpdated::class, times : 1);
});

0 comments on commit 434cb09

Please sign in to comment.