77 lines
2.1 KiB
PHP
77 lines
2.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Traits\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
/**
|
|
* ! Use this only on limited elements, (not on tags, or products, or posts for ex.)
|
|
*
|
|
* @template TModel of \Illuminate\Database\Eloquent\Model
|
|
*
|
|
* @property array<string,string|int|float|bool> $cacheConditions
|
|
*
|
|
* @mixin \Illuminate\Database\Eloquent\Model
|
|
*/
|
|
trait IsCachedAsCollection
|
|
{
|
|
public static function bootIsCachedAsCollection(): void
|
|
{
|
|
$flush = fn () => static::removeCached();
|
|
|
|
static::saved($flush);
|
|
static::deleted($flush);
|
|
}
|
|
|
|
/**
|
|
* @return \Illuminate\Database\Eloquent\Collection<int, static>
|
|
*/
|
|
public static function getCached(): Collection
|
|
{
|
|
/** @var \Illuminate\Database\Eloquent\Collection<int, static> */
|
|
return Cache::remember(static::getCacheKeyName(), 48 * 60 * 60, function () {
|
|
$query = static::query();
|
|
|
|
if (property_exists(static::class, 'cacheConditions')) {
|
|
// @phpstan-ignore property.staticAccess
|
|
$query->where(static::$cacheConditions);
|
|
}
|
|
|
|
$results = static::queryCached($query)->get();
|
|
|
|
return static::filterQuery($results);
|
|
});
|
|
}
|
|
|
|
public static function removeCached(): void
|
|
{
|
|
Cache::forget(static::getCacheKeyName());
|
|
}
|
|
|
|
/**
|
|
* @param \Illuminate\Database\Eloquent\Builder<static> $query
|
|
* @return \Illuminate\Database\Eloquent\Builder<static>
|
|
*/
|
|
protected static function queryCached(Builder $query): Builder
|
|
{
|
|
return $query;
|
|
}
|
|
|
|
/**
|
|
* @param \Illuminate\Database\Eloquent\Collection<int, static> $results
|
|
* @return \Illuminate\Database\Eloquent\Collection<int, static>
|
|
*/
|
|
protected static function filterQuery(Collection $results): Collection
|
|
{
|
|
return $results;
|
|
}
|
|
|
|
protected static function getCacheKeyName(): string
|
|
{
|
|
return 'model_cache_' . strtolower(class_basename(static::class));
|
|
}
|
|
}
|