> $ingredients_list Recipe list of ingredients. * @property \App\Models\Video|null $video_id Recipe video. * @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 bool $highlight Recipe highlight. * @property bool $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 RedirectableInterface, SchemaOrgInterface, SeoInterface, Sitemapable { use ActivityLog; use HasFactory; use IsRedirectable; use SchemaOrgTrait; use Searchable; use SeoTrait; /** * 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', 'product_id', 'preparation_time', 'cooking_time', 'nb_guests', 'difficulty', 'highlight', 'published', 'preparation_title', 'advice_title', 'advice_picto', 'advice_picto_alt', 'advice_picto_title', 'tips_title', 'tips_picto', 'tips_picto_alt', 'tips_picto_title', ]; /** * 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'], ]; /** * Get sortable virtual column. * * @var array */ public static $sortableVirtualColumn = [ 'ratings_avg_rate', ]; /** * Perform any actions required after the model boots. */ 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 $model) { self::resetCache(); Rating::resetCache($model); }); 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'); foreach (['advice_picto', 'tips_picto'] as $picto) { if (filled($model->getOriginal($picto))) { FileStorageHelper::removeOldFile($model, $picto); } } self::resetCache(); Rating::resetCache($model); }); static::deleted(function (self $model) { FileStorageHelper::removeFile($model, 'picture'); foreach (['advice_picto', 'tips_picto'] as $picto) { if (filled($model->getOriginal($picto))) { FileStorageHelper::removeOldFile($model, $picto); } } self::resetCache(); Rating::resetCache($model); }); } // * METHODS /** * Manage model fields. */ private static function manageFields(self $model): void { $model->slug = Str::slug($model->title); $model->picture = FileStorageHelper::storeFile($model, $model->picture, true); // Optional icons only if specified foreach (['advice_picto', 'tips_picto'] as $picto) { if (filled($model->{$picto})) { $model->{$picto} = FileStorageHelper::storeFile($model, $model->{$picto}, true); } } } /** * Asserts using validation that the label is unique. * * @throws \Illuminate\Validation\ValidationException If a range title already exists. */ private static function assertTitleIsUnique(?string $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. */ 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. */ 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. */ public function toSeoItem(): 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. */ private static function resetCache(): void { Cache::forget('publishedFirstHighlightedRecipe'); self::getFirstHighlighted(); Cache::forget('9publishedRecipesWithProducts'); self::get9PublishedWithProducts(); } /** * Get first published and highlighted recipe. */ public static function getFirstHighlighted(): ?Recipe { return self::query()->where('published', true)->where('highlight', true)->first(); } /** * Get 9 published recipes with products relations. */ public static function get9PublishedWithProducts(): Collection { return Cache::remember('9publishedRecipesWithProducts', 86400, function () { return self::query()->where('published', true)->with([ 'products', 'products.meat', 'products.submeat', 'consumptionMoments', ])->limit(9)->get(); }); } /** * toSitemapTag method */ public function toSitemapTag(): Url | string | array { return SitemapHelper::generateUrl('fo.recipes.show', ['slug' => $this->slug], $this); } /** * Determine if the model should be searchable. */ public function shouldBeSearchable(): bool { return $this->published === true; } /** * Create a SchemaOrg. * * @phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh */ public function toSchemaOrg(bool $asReference = false): \Spatie\SchemaOrg\Recipe { // @phpcs:enable $model = $this->load(['products', 'consumptionMoments', 'video', 'ratings']); // 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->consumptionMoments->pluck('title')->all(), $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) ); // Ratings. if ($model->ratings->count() && Rating::getAverageRating($model->ratings) > 2.0) { $schema->aggregateRating( Rating::toSchemaOrg($model->ratings) ); } // 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; } /** * Build list from the preparation WYSIWYG content * * @return array|string|null */ public function getPreparationStepsSchema(): array|string|null { // multi-line content accepted preg_match_all('/]*>(.*?)<\/li>/is', (string) $this->preparation, $matches); $steps = collect($matches[1]) ->map(fn(string $step) => trim(html_entity_decode(strip_tags($step)))) ->filter() ->values(); if ($steps->isNotEmpty()) { return $steps ->map(fn(string $text, int $index) => Schema::howToStep() ->position($index + 1) ->text($text)) ->all(); } // no list in the WYSIWYG returning raw text $text = trim(html_entity_decode(strip_tags((string) $this->preparation))); return $text !== '' ? $text : null; } // * REDIRECTIONS. /** * Get the front url of this model. * Should return the model.show route, with all binded elements if needed. */ public function getFrontUrl(string $modelKey): string { return route('fo.recipes.show', $modelKey); } // * RELATIONSHIPS /** * Get all of the consumption moments for the recipe. */ public function consumptionMoments(): BelongsToMany { return $this->belongsToMany(ConsumptionMoment::class); } /** * Get the video for the recipe. */ public function video(): BelongsTo { return $this->belongsTo(Video::class); } /** * Get all of the products for the recipe. */ public function products(): MorphToMany { return $this->morphToMany(Product::class, 'productable')->with(['meat', 'submeat']); } /** * Get the nutritionnal values for the product. */ public function ratings(): MorphMany { return $this->morphMany(Rating::class, 'rating'); } /** * Determine whether the advice section should be displayed. */ public function hasAdvice(): bool { return filled($this->advice_title) && self::hasText($this->advice); } /** * Determine whether the nutrition tip section. */ public function hasTips(): bool { return filled($this->tips_title) && self::hasText($this->tips); } /** * Determine whether a WYSIWYG HTML content contains visible text. */ private static function hasText(?string $html): bool { return filled(trim(html_entity_decode(strip_tags((string) $html)))); } }