ldc-legaulois/app/Traits/Models/IsCachedAsCollection.php

96 lines
2.5 KiB
PHP
Raw Permalink Normal View History

2024-01-10 14:49:46 +01:00
<?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.)
*
2026-09-25 16:25:31 +02:00
* @property array<string,string|int|float|bool> $cacheConditions
* Eloquent condition to cache elements (to be used in where statement).
2024-01-10 14:49:46 +01:00
*/
trait IsCachedAsCollection
{
/**
* Get all available instances from cache.
* If cache was reset, it will fetch them from DB.
*
2024-04-19 10:08:36 +02:00
* @return \Illuminate\Database\Eloquent\Collection<(int|string), mixed>
2026-09-25 16:25:31 +02:00
*
2024-04-19 10:08:36 +02:00
* @phpstan-ignore-next-line
2024-01-10 14:49:46 +01:00
*/
2024-04-19 10:08:36 +02:00
public static function getCached(): \Illuminate\Database\Eloquent\Collection
2024-01-10 14:49:46 +01:00
{
2026-09-25 16:25:31 +02:00
if (! Cache::has(static::getCacheKeyName())) {
2024-01-10 14:49:46 +01:00
try {
static::setCached();
} catch (QueryException $e) {
report($e);
2026-09-25 16:25:31 +02:00
2024-06-21 15:26:40 +02:00
return \Illuminate\Database\Eloquent\Collection::make();
2024-01-10 14:49:46 +01:00
}
}
2026-09-25 16:25:31 +02:00
2024-01-10 14:49:46 +01:00
return Cache::get(static::getCacheKeyName());
}
/**
* Remove cached elements.
2024-01-10 14:49:46 +01:00
*/
public static function removeCached(): void
{
Cache::forget(static::getCacheKeyName());
}
/**
* Put all instances into cache.
*/
protected static function setCached(): void
{
$conditions = [];
if (property_exists(get_called_class(), 'cacheConditions')) {
2024-04-19 10:08:36 +02:00
// @phpstan-ignore-next-line
2024-01-10 14:49:46 +01:00
$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.
2024-01-10 14:49:46 +01:00
*/
2026-09-25 16:25:31 +02:00
protected static function queryCached(Builder $query): Builder
2024-01-10 14:49:46 +01:00
{
return $query;
}
/**
* Change query for cached elements.
2024-01-10 14:49:46 +01:00
*/
2026-09-25 16:25:31 +02:00
protected static function filterQuery(Collection $results): Collection
2024-01-10 14:49:46 +01:00
{
return $results;
}
/**
* Get the class basename.
2024-01-10 14:49:46 +01:00
*/
protected static function getCacheKeyName(): string
{
return static::getCallClassBaseName();
}
/**
* Get the class basename.
2024-01-10 14:49:46 +01:00
*/
protected static function getCallClassBaseName(): string
{
return str_replace(__NAMESPACE__ . '\\', '', get_called_class());
}
}