384 lines
13 KiB
PHP
384 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\Recipes\DifficultyEnum;
|
|
use App\Lib\Helpers\FileStorageHelper;
|
|
use App\Lib\Helpers\ToolboxHelper;
|
|
use App\Rules\IsValidVimeoId;
|
|
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 Laravel\Scout\Searchable;
|
|
use Spatie\SchemaOrg\Schema;
|
|
use Uwil\SchemaOrg\Laravel\Interfaces\SchemaOrgInterface;
|
|
use Uwil\SchemaOrg\Laravel\Traits\SchemaOrgTrait;
|
|
use Uwil\Seo\Laravel\Interfaces\SeoInterface;
|
|
use Uwil\Seo\Laravel\Traits\SeoTrait;
|
|
use Uwil\Seo\Laravel\Objects\SeoItem;
|
|
use Spatie\Sitemap\Contracts\Sitemapable;
|
|
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 array<array<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, SchemaOrgInterface
|
|
{
|
|
use ActivityLog;
|
|
use HasFactory;
|
|
use SeoTrait;
|
|
use Searchable;
|
|
use SchemaOrgTrait;
|
|
|
|
/**
|
|
* 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',
|
|
];
|
|
|
|
/**
|
|
* Get model's setting to apply on scout search (meilisearch).
|
|
*
|
|
* @var array
|
|
*/
|
|
public static $searchSettings = [
|
|
'filterableAttributes' => ['title', 'preparation', 'advice', 'published'],
|
|
'sortableAttributes' => ['title', 'preparation', 'advice']
|
|
];
|
|
|
|
/**
|
|
* 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::remember('9publishedRecipesWithProducts', 86400, function () {
|
|
return self::query()->where('published', true)->with([
|
|
'products',
|
|
'products.meat',
|
|
'products.submeat',
|
|
'consumptionMoment'
|
|
])->limit(9)->get();
|
|
});
|
|
}
|
|
|
|
/**
|
|
* toSitemapTag method
|
|
*
|
|
* @return \Spatie\Sitemap\Tags\Url|string|array
|
|
*/
|
|
public function toSitemapTag(): \Spatie\Sitemap\Tags\Url|string|array
|
|
{
|
|
return SitemapHelper::generateUrl('fo.recipes.show', ['slug' => $this->slug], $this);
|
|
}
|
|
|
|
/**
|
|
* Determine if the model should be searchable.
|
|
*
|
|
* @return boolean
|
|
*/
|
|
public function shouldBeSearchable(): bool
|
|
{
|
|
return $this->published === true;
|
|
}
|
|
|
|
/**
|
|
* Create a SchemaOrg.
|
|
*
|
|
* @param boolean $asReference
|
|
* @return \Spatie\SchemaOrg\Recipe
|
|
*/
|
|
public function toSchemaOrg(bool $asReference = false): \Spatie\SchemaOrg\Recipe
|
|
{
|
|
$model = $this->load(['consumptionMoment']);
|
|
|
|
// Main.
|
|
$schema = Schema::Recipe()
|
|
->name($model->title)
|
|
->description($model->seo_description)
|
|
->url(route('fo.recipes.show', $model))
|
|
->recipeCategory([
|
|
$model->consumptionMoment->title,
|
|
$model->difficulty->label(),
|
|
])
|
|
->recipeInstructions($model->tips)
|
|
->dateCreated($model->created_at)
|
|
->dateModified($model->updated_at)
|
|
->datePublished($model->created_at)
|
|
->cookTime(
|
|
Schema::duration()->setProperty("@value", $model->formatDurationIso($model->cooking_time))
|
|
)
|
|
->prepTime(
|
|
Schema::duration()->setProperty("@value", $model->formatDurationIso($model->preparation_time))
|
|
)
|
|
->totalTime(
|
|
Schema::duration()->setProperty("@value", $model->formatDurationIso(
|
|
$model->cooking_time + $model->preparation_time
|
|
))
|
|
)
|
|
->author($model->getOrganizationSchema())
|
|
->creator($model->getOrganizationSchema())
|
|
->image(
|
|
Schema::imageObject()
|
|
->url(asset($model->picture))
|
|
->headline($model->picture_title)
|
|
);
|
|
|
|
// Steps associated.
|
|
preg_match_all('/<li>(.*?)<\/li>/', $model->preparation, $step);
|
|
$schema->steps($step[1]);
|
|
|
|
// Ingredients associated.
|
|
$ingredientsList = collect($model->ingredients_list)
|
|
->map(function ($item) {
|
|
// @phpstan-ignore ternary.elseUnreachable
|
|
return trim(($item['label_unit'] !== null ? $item['label_unit'] : '') . ' ' . $item['label_value']);
|
|
})->implode(', ');
|
|
$schema->recipeIngredient($ingredientsList);
|
|
|
|
// Products associated.
|
|
if (!$asReference) {
|
|
$linkedProducts = $model->products->map(function (Product $product) {
|
|
return $product->toSchemaOrg(true);
|
|
})->toArray();
|
|
$schema->subjectOf($linkedProducts);
|
|
}
|
|
|
|
// Video associated.
|
|
if ($model->video_id) {
|
|
$url = (IsValidVimeoId::validates($model->video_id))
|
|
? "https://player.vimeo.com/video/$model->video_id"
|
|
: "https://www.youtube.com/embed/$model->video_id";
|
|
$schema->associatedMedia(
|
|
Schema::mediaObject()
|
|
->name($model->video->title)
|
|
->productionCompany($model->getOrganizationSchema())
|
|
->embedUrl($url)
|
|
);
|
|
}
|
|
|
|
return $schema;
|
|
}
|
|
|
|
// * 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']);
|
|
}
|
|
}
|