ldc-legaulois/app/Models/Recipe.php
2024-10-24 09:42:37 +00:00

283 lines
9 KiB
PHP

<?php
namespace App\Models;
use App\Enums\Recipes\DifficultyEnum;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Uwil\Seo\Laravel\Interfaces\SeoInterface;
use Uwil\Seo\Laravel\Traits\SeoTrait;
use Uwil\Seo\Laravel\Objects\SeoItem;
use Spatie\Sitemap\Contracts\Sitemapable;
use Spatie\Sitemap\Tags\Url;
use Uwil\SitemapGenerator\Lib\SitemapHelper;
/**
* @property string $slug Recipe slug.
* @property string $title Recipe title.
* @property string $tips Recipe tips.
* @property string $picture Recipe picture.
* @property string $picture_alt Picture alt attribute.
* @property string $picture_title Picture title attribute.
* @property string $advice Recipe advice.
* @property string $preparation Recipe preparation.
* @property string $ingredients_list Recipe list of ingredients.
* @property \App\Models\Video|null $video_id Recipe video.
* @property \App\Models\ConsumptionMoment $consumption_moment_id Recipe consumption moment.
* @property int $preparation_time Recipe preparation time.
* @property int $cooking_time Recipe cooking time.
* @property int $nb_guests Number of reference persons for
* ingredient list of the recipe.
* @property \App\Enums\Recipes\DifficultyEnum $difficulty Recipe difficulty.
* @property boolean $highlight Recipe highlight.
* @property boolean $published Recipe published.
* @property-read \Illuminate\Support\Carbon $created_at Created date.
* @property-read \Illuminate\Support\Carbon $updated_at Updated date.
*/
class Recipe extends Model implements SeoInterface, Sitemapable
{
use ActivityLog;
use HasFactory;
use SeoTrait;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'seo_title',
'seo_description',
'slug',
'title',
'tips',
'picture',
'picture_alt',
'picture_title',
'advice',
'preparation',
'ingredients_list',
'video_id',
'consumption_moment_id',
'product_id',
'preparation_time',
'cooking_time',
'nb_guests',
'difficulty',
'highlight',
'published',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'ingredients_list' => 'array',
'difficulty' => DifficultyEnum::class,
'highlight' => 'boolean',
'published' => 'boolean',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
self::assertTitleIsUnique($model->title, $model->getKey());
self::setHighlightValue($model);
self::manageFields($model);
});
static::created(function () {
self::resetCache();
});
static::updating(function (self $model) {
self::assertTitleIsUnique($model->title, $model->getKey());
self::setHighlightValue($model);
self::manageFields($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
self::resetCache();
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
self::resetCache();
});
}
// * METHODS
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
$model->slug = Str::slug($model->title);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
/**
* Asserts using validation that the label is unique.
*
* @param string|null $title
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If a range title already exists.
*/
private static function assertTitleIsUnique(string|null $title, ?int $id = null): void
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
}
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
public static function setHighlightValue(self $model): void
{
/** @var \App\Models\Recipe|null $recipeOld */
$recipeOld = Recipe::query()->where('highlight', true)->first();
if ($recipeOld && $recipeOld->getkey() !== $model->getkey() && $model->highlight) {
$recipeOld->highlight = false;
$recipeOld->saveQuietly();
}
}
/**
* Convert minutes times format to hours and minutes times format.
*
* @param integer $time
* @return string
*/
public static function convertTime(int $time): string
{
return sprintf(
'%s%s',
floor($time / 60) ? floor($time / 60) . 'h' : '',
// @phpstan-ignore-next-line
(($time - floor($time / 60) * 60 < 10) && floor($time / 60) > 0 ? '0' : '') .
$time -
floor($time / 60) * 60 .
'min',
);
}
/**
* Transform to seoModel.
*
* @return \Uwil\Seo\Laravel\Objects\SeoItem
*/
public function toSeoItem(): \Uwil\Seo\Laravel\Objects\SeoItem
{
return new SeoItem(
'recipe',
$this->seo_title,
$this->seo_description,
$this->published ?? false,
\route(\config('seo.bo_route_prefix') . $this->getTable() . '.edit', $this),
route('fo.recipes.show', $this->slug)
);
}
/**
* Reset all cache elements related to this model.
*
* @return void
*/
private static function resetCache(): void
{
Cache::forget('publishedFirstHighlightedRecipe');
self::getFirstHighlighted();
Cache::forget('9publishedRecipesWithProducts');
self::get9PublishedWithProducts();
}
/**
* Get first published and highlighted recipe.
*
* @return \App\Models\Recipe|null
*/
public static function getFirstHighlighted(): \App\Models\Recipe|null
{
return self::query()->where('published', true)->where('highlight', true)->first();
}
/**
* Get 9 published recipes with products relations.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function get9PublishedWithProducts(): \Illuminate\Database\Eloquent\Collection
{
return Cache::rememberForever('9publishedRecipesWithProducts', function () {
return self::query()->where('published', true)->with([
'products',
'products.meat',
'products.submeat',
'consumptionMoment'
])->limit(9)->get();
});
}
/**
* toSitemapTag method
*
* @return Url|string|array
*/
public function toSitemapTag(): Url | string | array
{
$model = $this;
$route = 'fo.recipes.show';
$params = ['slug' => $model->slug];
return SitemapHelper::generateUrl($route, $params, $model);
}
// * RELATIONSHIPS
/**
* Get all of the consumption moment for the recipe.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function consumptionMoment(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(ConsumptionMoment::class);
}
/**
* Get the video for the recipe.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function video(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(Video::class);
}
/**
* Get all of the products for the recipe.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function products(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphToMany(Product::class, 'productable')->with(['meat', 'submeat']);
}
}