Add nutrient calculation for recipe volumes

This commit is contained in:
Christopher C. Wells 2021-04-18 13:46:20 -07:00
parent 809e3ca7d7
commit fb3fa3dd1d
3 changed files with 19 additions and 10 deletions

View File

@ -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
{

View File

@ -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');
}
}

View File

@ -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"}();
}
/**