mirror of https://github.com/kcal-app/kcal.git
Add nutrient calculation for recipe volumes
This commit is contained in:
parent
809e3ca7d7
commit
fb3fa3dd1d
|
@ -80,6 +80,9 @@ use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
|||
* @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\RecipeSeparator[] $separators
|
||||
* @property-read int|null $separators_count
|
||||
* @property-read Collection $units_supported
|
||||
* @property float|null $volume
|
||||
* @property-read string|null $volume_formatted
|
||||
* @method static \Illuminate\Database\Eloquent\Builder|Recipe whereVolume($value)
|
||||
*/
|
||||
final class Recipe extends Model implements HasMedia
|
||||
{
|
||||
|
|
|
@ -65,6 +65,9 @@ trait Ingredient
|
|||
if (!empty($this->serving_weight)) {
|
||||
$supported = $supported->merge($units->where('type', 'weight'));
|
||||
}
|
||||
if (isset($this->volume) && !empty($this->volume)) {
|
||||
$supported = $supported->merge($units->where('type', 'volume'));
|
||||
}
|
||||
return $supported->sortBy('label');
|
||||
}
|
||||
}
|
||||
|
|
|
@ -175,6 +175,8 @@ class Nutrients
|
|||
|
||||
/**
|
||||
* Calculate a nutrient amount for a recipe.
|
||||
*
|
||||
* Weight base unit is grams, volume base unit is cups.
|
||||
*/
|
||||
public static function calculateRecipeNutrientAmount(
|
||||
Recipe $recipe,
|
||||
|
@ -182,18 +184,19 @@ class Nutrients
|
|||
float $amount,
|
||||
string $fromUnit
|
||||
): float {
|
||||
if ($fromUnit === 'oz') {
|
||||
return $amount * self::$gramsPerOunce / $recipe->weight * $recipe->{"{$nutrient}Total"}();
|
||||
}
|
||||
elseif ($fromUnit === 'serving') {
|
||||
if ($fromUnit === 'serving') {
|
||||
// Use "per serving" methods directly.
|
||||
return $recipe->{"{$nutrient}PerServing"}() * $amount;
|
||||
}
|
||||
elseif ($fromUnit === 'gram') {
|
||||
return $amount / $recipe->weight * $recipe->{"{$nutrient}Total"}();
|
||||
}
|
||||
else {
|
||||
throw new \DomainException("Unsupported recipe unit: {$fromUnit}");
|
||||
}
|
||||
$multiplier = match ($fromUnit) {
|
||||
'oz' => $amount * self::$gramsPerOunce / $recipe->weight,
|
||||
'gram' => $amount / $recipe->weight,
|
||||
'tsp' => $amount / 48 / $recipe->volume,
|
||||
'tbsp' => $amount / 16 / $recipe->volume,
|
||||
'cup' => $amount / $recipe->volume,
|
||||
default => throw new \DomainException("Unsupported recipe unit: {$fromUnit}"),
|
||||
};
|
||||
return $multiplier * $recipe->{"{$nutrient}Total"}();
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
Loading…
Reference in New Issue