ldc-gen-game-web/app/Traits/Models/IsCachedAsCollection.php
2026-10-20 12:27:49 +02:00

94 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Traits\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
/**
* ! Use this only on limited elements, (not on tags, or products, or posts for ex.)
*
* @property array<string,string|int|float|bool> $cacheConditions
* Eloquent condition to cache elements (to be used in where statement).
*/
trait IsCachedAsCollection
{
/**
* Get all available instances from cache.
* If cache was reset, it will fetch them from DB.
*
* @return \Illuminate\Database\Eloquent\Collection|Collection<(int|string), mixed>
*/
public static function getCached(): Collection
{
if (! Cache::has(static::getCacheKeyName())) {
try {
static::setCached();
} catch (QueryException $e) {
report($e);
return \collect();
}
}
return Cache::get(static::getCacheKeyName());
}
/**
* Remove cached elements
*/
public static function removeCached(): void
{
Cache::forget(static::getCacheKeyName());
}
/**
* Put all instances into cache.
*/
protected static function setCached(): void
{
$conditions = [];
if (property_exists(static::class, 'cacheConditions')) {
$conditions = collect(static::class::${'cacheConditions'})->all();
}
Cache::put(static::getCacheKeyName(), static::queryCached(static::query())
->where($conditions)->get()
->pipe(fn (Collection $collection): Collection => \call_user_func(self::filterQuery(...), $collection)));
}
/**
* Change query for cached elements
*/
protected static function queryCached(Builder $query): Builder
{
return $query;
}
/**
* Change query for cached elements
*/
protected static function filterQuery(Collection $results): Collection
{
return $results;
}
/**
* Get the class basename
*/
protected static function getCacheKeyName(): string
{
return static::getCallClassBaseName();
}
/**
* Get the class basename
*/
protected static function getCallClassBaseName(): string
{
return str_replace(__NAMESPACE__ . '\\', '', static::class);
}
}