ldc-volena/app/Traits/Models/IsCachedAsCollection.php
2023-11-13 11:56:06 +01:00

103 lines
2.6 KiB
PHP

<?php
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 private static array $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
*/
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
*
* @return void
*/
public static function removeCached(): void
{
Cache::forget(static::getCacheKeyName());
}
/**
* Put all instances into cache.
*
* @return void
*/
protected static function setCached(): void
{
$conditions = [];
if (property_exists(get_called_class(), 'cacheConditions')) {
$conditions = collect(static::${'cacheConditions'})->all();
}
Cache::put(static::getCacheKeyName(), static::queryCached(static::query())
->where($conditions)->get()
->pipe(fn (Collection $collection) => \call_user_func([self::class, 'filterQuery'], $collection)));
}
/**
* Change query for cached elements
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
protected static function queryCached(Builder $query): Builder
{
return $query;
}
/**
* Change query for cached elements
*
* @param \Illuminate\Support\Collection $results
* @return \Illuminate\Support\Collection
*/
protected static function filterQuery(Collection $results): Collection
{
return $results;
}
/**
* Get the class basename
*
* @return string
*/
protected static function getCacheKeyName(): string
{
return static::getCallClassBaseName();
}
/**
* Get the class basename
*
* @return string
*/
protected static function getCallClassBaseName(): string
{
return str_replace(__NAMESPACE__ . '\\', '', get_called_class());
}
}