Skip to content

Commit

Permalink
finish route that allows for updating a permanent cache
Browse files Browse the repository at this point in the history
  • Loading branch information
david-d-h committed Jun 15, 2024
1 parent c8ad011 commit ea67f6d
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 44 deletions.
14 changes: 0 additions & 14 deletions routes/api.php

This file was deleted.

27 changes: 27 additions & 0 deletions routes/permanent-cache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Vormkracht10\PermanentCache\CachesValue;

Route::get('/permanent-cache/{class}/update', function (Request $request, string $class) {
/** @var class-string<CachesValue> $class */
$class = decrypt($class);

$parameters = ($parameters = $request->query('parameters'))
? Arr::wrap(decrypt($parameters))
: [];

if (
! class_exists($class) ||
! in_array(CachesValue::class, class_uses_recursive($class))
) {
return response()->json([
'error' => 'the given class does not exist or does not use the ['.CachesValue::class.'] trait',
], 400);
}

$data = $class::updateAndGet($parameters ?? []);

return response()->json(compact('data'));
})->name('permanent-cache.update');
42 changes: 19 additions & 23 deletions src/CachesValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,7 @@ final public static function update($parameters = [])
{
$instance = app()->make(static::class, $parameters);

dispatch(
$instance
);
dispatch($instance);
}

/**
Expand All @@ -139,9 +137,7 @@ final public static function updateAndGet($parameters = [])
{
$instance = app()->make(static::class, $parameters);

dispatch(
$instance
)->onConnection('sync');
dispatch($instance)->onConnection('sync');

return static::get($parameters);
}
Expand All @@ -161,7 +157,7 @@ final public static function get($parameters = [], $default = null, bool $update

if (
$update ||
!$cache->has($cacheKey)
! $cache->has($cacheKey)
) {
return static::updateAndGet($parameters ?? []);
}
Expand Down Expand Up @@ -189,7 +185,7 @@ final public function getMeta($parameters = []): mixed
*/
final protected function value($default = null): mixed
{
if (is_subclass_of(static::class, CachedComponent::class) && !is_null($default)) {
if (is_subclass_of(static::class, CachedComponent::class) && ! is_null($default)) {
throw new \Exception("A cached component can't have a default return value");
}

Expand All @@ -212,19 +208,20 @@ public function getShortName(): string
}

/// Default implementation for the `\Scheduled::schedule` method.
/** @param CallbackEvent $callback */

/** @param CallbackEvent $callback */
public static function schedule($callback)
{
if (!is_a(static::class, Scheduled::class, true)) {
throw new \Exception("Can't schedule a cacher that does not implement the [" . Scheduled::class . '] interface');
if (! is_a(static::class, Scheduled::class, true)) {
throw new \Exception("Can't schedule a cacher that does not implement the [".Scheduled::class.'] interface');
}

$reflection = new ReflectionClass(static::class);

$concrete = $reflection->getProperty('expression')->getDefaultValue();

if (is_null($concrete)) {
throw new \Exception('Either the Cached::$expression property or the [' . __METHOD__ . '] method must be overridden by the user.');
throw new \Exception('Either the Cached::$expression property or the ['.__METHOD__.'] method must be overridden by the user.');
}

$callback->cron($concrete);
Expand Down Expand Up @@ -267,7 +264,7 @@ public static function getCacheKey(?array $parameters = [], ?string $store = nul
->getDefaultValue();

if (
!is_null($store) &&
! is_null($store) &&
strpos($store, ':')
) {
$cacheStore = substr($store, 0, strpos($store, ':'));
Expand All @@ -280,7 +277,7 @@ public static function getCacheKey(?array $parameters = [], ?string $store = nul
$cacheKey ??= preg_replace('/[^A-Za-z0-9]+/', '_', strtolower(Str::snake($class)));

if ($parameters) {
$cacheKey .= ':' . http_build_query($parameters);
$cacheKey .= ':'.http_build_query($parameters);
}

return [$cacheStore, $cacheKey];
Expand All @@ -290,36 +287,35 @@ public function getMarker(array $parameters = [], $close = false): string
{
[$cacheStore, $cacheKey] = $this::store($parameters ?? $this->getParameters());

$marker = $cacheStore . ':' . $cacheKey;
$marker = $cacheStore.':'.$cacheKey;

if (config('permanent-cache.components.markers.hash')) {
$marker = md5($marker);
}

return '<!--' . ($close ? '/' : '') . $marker . '-->';
return '<!--'.($close ? '/' : '').$marker.'-->';
}

public function addMarkers($value): mixed
{
if (
!config('permanent-cache.components.markers.enabled') ||
!is_subclass_of($this, CachedComponent::class)
! config('permanent-cache.components.markers.enabled') ||
! is_subclass_of($this, CachedComponent::class)
) {
return $value;
}

return $this->getMarker() . $value . $this->getMarker(close: true);
return $this->getMarker().$value.$this->getMarker(close: true);
}


public function getRefreshRoute()
{
$class = get_class($this);
$props =
collect((new ReflectionClass($this))->getProperties(\ReflectionProperty::IS_PUBLIC))
->where('class', __CLASS__)
->mapWithKeys(fn ($prop) => [$prop->name => $this->{$prop->name}])
->toArray();
->where('class', __CLASS__)
->mapWithKeys(fn ($prop) => [$prop->name => $this->{$prop->name}])
->toArray();

return route('permanent-cache.update', ['data' => encrypt([$class, $props])]);
}
Expand Down
2 changes: 1 addition & 1 deletion src/PermanentCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public function caches($registeredCaches): self
$cacheInstance = $this->app->make($cache, $parameters);

if ([] !== $events = $cacheInstance->getListenerEvents()) {
foreach($events as $event) {
foreach ($events as $event) {
Event::listen($event, fn ($e) => $cacheInstance->handle($e));
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/PermanentCacheServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ public function configurePackage(Package $package): void
$package->name('laravel-permanent-cache')
->hasCommands(
PermanentCachesStatusCommand::class,
UpdatePermanentCachesCommand::class
UpdatePermanentCachesCommand::class,
)
->hasRoute('api')
->hasRoute('permanent-cache')
->hasConfigFile();
}

Expand All @@ -28,11 +28,10 @@ public function registeringPackage()

public function bootingPackage()
{
$this->callAfterResolving(
Schedule::class,
$this->callAfterResolving(Schedule::class,
fn (Schedule $schedule) => collect(Facades\PermanentCache::configuredCaches())
->filter(fn ($cacher) => is_a($cacher, Scheduled::class))
->each(fn ($cacher) => $cacher->schedule($schedule->job($cacher)))
->each(fn ($cacher) => $cacher->schedule($schedule->job($cacher))),
);
}
}
1 change: 0 additions & 1 deletion tests/TestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace Vormkracht10\PermanentCache\Tests;

use Illuminate\Database\Eloquent\Factories\Factory;
use Orchestra\Testbench\TestCase as Orchestra;
use Vormkracht10\PermanentCache\PermanentCacheServiceProvider;

Expand Down

0 comments on commit ea67f6d

Please sign in to comment.