ldc-gen-game-web/app/Traits/Models/IsCachedAsCollection.php

95 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2023-08-21 10:22:07 +02:00
<?php
2026-10-02 12:09:46 +02:00
declare(strict_types=1);
2023-08-21 10:22:07 +02:00
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.)
*
2026-10-02 12:09:46 +02:00
* @property array<string,string|int|float|bool> $cacheConditions
* Eloquent condition to cache elements (to be used in where statement).
2023-08-21 10:22:07 +02:00
*/
trait IsCachedAsCollection
{
/**
* Get all available instances from cache.
* If cache was reset, it will fetch them from DB.
*
2026-10-02 12:09:46 +02:00
* @return \Illuminate\Database\Eloquent\Collection|Collection<(int|string), mixed>
2023-08-21 10:22:07 +02:00
*/
public static function getCached(): Collection
{
2026-10-02 12:09:46 +02:00
if (! Cache::has(static::getCacheKeyName())) {
2023-08-21 10:22:07 +02:00
try {
static::setCached();
} catch (QueryException $e) {
report($e);
2026-10-02 12:09:46 +02:00
2023-08-21 10:22:07 +02:00
return \collect();
}
}
2026-10-02 12:09:46 +02:00
2023-08-21 10:22:07 +02:00
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 = [];
2026-10-02 12:09:46 +02:00
if (property_exists(static::class, 'cacheConditions')) {
$conditions = collect(static::class::${'cacheConditions'})->all();
2023-08-21 10:22:07 +02:00
}
Cache::put(static::getCacheKeyName(), static::queryCached(static::query())
->where($conditions)->get()
2026-10-02 12:09:46 +02:00
->pipe(fn (Collection $collection): Collection => \call_user_func(self::filterQuery(...), $collection)));
2023-08-21 10:22:07 +02:00
}
/**
* 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
{
2026-10-02 12:09:46 +02:00
return str_replace(__NAMESPACE__ . '\\', '', static::class);
2023-08-21 10:22:07 +02:00
}
}