diff --git a/app/Models/IngredientAmount.php b/app/Models/IngredientAmount.php index af366ab..35f739f 100644 --- a/app/Models/IngredientAmount.php +++ b/app/Models/IngredientAmount.php @@ -5,7 +5,6 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; -use JetBrains\PhpStorm\Pure; /** * @property float amount @@ -49,10 +48,31 @@ class IngredientAmount extends Model /** * Get total calories for the ingredient amount. */ - #[Pure] public function calories(): float { + public function calories(): float { return $this->ingredient->calories * $this->amount * $this->unitMultiplier(); } + /** + * Get total protein for the ingredient amount. + */ + public function protein(): float { + return $this->ingredient->protein * $this->amount * $this->unitMultiplier(); + } + + /** + * Get total fat for the ingredient amount. + */ + public function fat(): float { + return $this->ingredient->fat * $this->amount * $this->unitMultiplier(); + } + + /** + * Get total carbohydrates for the ingredient amount. + */ + public function carbohydrates(): float { + return $this->ingredient->carbohydrates * $this->amount * $this->unitMultiplier(); + } + /** * Get the multiplier for the ingredient unit and ingredient amount unit. */ diff --git a/app/Models/Recipe.php b/app/Models/Recipe.php index 6001bfb..5c63cfe 100644 --- a/app/Models/Recipe.php +++ b/app/Models/Recipe.php @@ -5,8 +5,10 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; -use Illuminate\Database\Eloquent\Relations\HasManyThrough; +/** + * @property \App\Models\IngredientAmount[] ingredientAmounts + */ class Recipe extends Model { use HasFactory; @@ -29,4 +31,48 @@ class Recipe extends Model public function ingredientAmounts(): HasMany { return $this->hasMany(IngredientAmount::class); } + + /** + * Get total recipe calories. + */ + public function calories(): float { + return $this->sumNutrient('calories'); + } + + /** + * Get total recipe protein. + */ + public function protein(): float { + return $this->sumNutrient('protein'); + } + + /** + * Get total recipe fat. + */ + public function fat(): float { + return $this->sumNutrient('fat'); + } + + /** + * Get total recipe carbohydrates. + */ + public function carbohydrates(): float { + return $this->sumNutrient('carbohydrates'); + } + + /** + * Sum a specific nutrient for all ingredient amounts. + * + * @param string $nutrient + * Nutrient to sum ("calories", "protein", "fat", or "carbohydrates"). + * + * @return float + */ + private function sumNutrient(string $nutrient): float { + $sum = 0; + foreach ($this->ingredientAmounts as $ingredientAmount) { + $sum += $ingredientAmount->{$nutrient}(); + } + return $sum; + } }