> $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 */ 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 */ 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(['products', 'consumptionMoment', 'video']); // Main. $schema = Schema::Recipe() ->name($model->title) ->description($model->seo_description) ->url(route('fo.recipes.show', $model->slug)) ->inLanguage(config('schema-org.website.languages')) ->keywords('recette') ->recipeCategory([ $model->consumptionMoment->title, $model->difficulty->label(), ]) ->recipeCuisine("Française") ->recipeInstructions($model->tips) ->dateCreated($model->created_at) ->dateModified($model->updated_at) ->datePublished($model->created_at) ->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) ) ->aggregateRating( Schema::aggregateRating() ->ratingValue(10) ->bestRating(10) ->worstRating(0) ->ratingCount(1) ->reviewCount(1) ); // Cooking time associated. if ($model->cooking_time) { $schema->cookTime( Schema::duration()->setProperty("@value", $model->formatDurationIso($model->cooking_time)) ); } // Steps associated. preg_match_all('/
  • (.*?)<\/li>/', $model->preparation, $step); $schema->steps($step[1]); // Ingredients associated. $ingredientsList = collect($model->ingredients_list) ->map(function ($item) { return trim( // @phpstan-ignore ternary.elseUnreachable ($item['value'] !== null ? $item['value'] : '') . ' ' . // @phpstan-ignore ternary.elseUnreachable ($item['label_unit'] !== null ? $item['label_unit'] : '') . ' ' . $item['label_value'] ); }) ->all(); $schema->ingredients($ingredientsList); // Products associated. $productsAssociated = $model->products->where('published', true)->values(); if ($productsAssociated->count() && !$asReference) { $linkedProducts = $productsAssociated->map(function (Product $product) { return $product->toSchemaOrg(true); })->toArray(); $schema->subjectOf($linkedProducts); // Nutritionnal values. $allNutritionnalValues = $productsAssociated->map(function (Product $productModel) { if ($productModel->getNutritionnalValue()) { return collect($productModel->getNutritionnalValue()->toArray()) // @phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundBeforeLastUsed ->reject(function ($value, $key) { return str_contains($key, '_percent') || in_array($key, [ 'id', 'product_id', 'created_at', 'updated_at' ]); }) ->toArray(); } else { return []; } })->reduce(function (?array $carry, array $item) { foreach ($item as $key => $value) { $carry[$key] = ($carry[$key] ?? 0) + $value; } return $carry; }); if ($allNutritionnalValues) { $schema->nutrition( Schema::nutritionInformation() ->carbohydrateContent($allNutritionnalValues['carbohydrates']) ->fatContent($allNutritionnalValues['fat']) ->proteinContent($allNutritionnalValues['protein']) ->sugarContent($allNutritionnalValues['sugar']) ); } } //end if // Video associated. if ($model->video_id && $model->video->published) { $schema->associatedMedia($model->video->toSchemaOrg()); } 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']); } }