karlomikus/recipe-utils

Utilities for extracting normalized ingredient data from recipes

0.13.1 2024-11-21 17:07 UTC

This package is auto-updated.

Last update: 2024-11-21 17:08:29 UTC


README

GitHub Actions Workflow Status Packagist Version GitHub License

Utilities for extracting ingredient data from (mostly cocktail) recipes into structured objects.

Install

Install via composer

$ composer require karlomikus/recipe-utils

Parser usage

All parse methods return object of type Kami\RecipeUtils\RecipeIngredient.

Supported formats:

  • Variable amounts and fractional amounts: "1 - 2", "0.5 to 1", "½ or 2 1/5"
  • Comments are anything after comma or anything in brackets: "12 ml ingredient, preferebly something specific"
  • Basic units mostly used in cocktails: ml, cl, oz, sprigs, dashes, etc...
<?php

declare(strict_types=1);

use Kami\RecipeUtils\Parser\Parser;
use Kami\RecipeUtils\Parser\UnitParser;
use Kami\RecipeUtils\UnitConverter\Units;

$ingredientParser = new Parser();

// Parse a single ingredient line
$ingredient = $ingredientParser->parseLine('30 ml Tequila reposado (preferebly Patron)');
var_dump($ingredient);
// Output:
// $ingredient->amount === '30'
// $ingredient->units === 'ml'
// $ingredient->name === 'Tequila reposado'
// $ingredient->comment === 'preferebly Patron'
// $ingredient->source === '30 ml Tequila reposado'

// Parse a line and convert units if possible
$ingredient = $ingredientParser->parseLine('1/2 - 1 ounce lime juice (freshly squeezed)', Units::Ml);
var_dump($ingredient);
// Output:
// $ingredient->amount === 15.0
// $ingredient->amount_max === 30.0
// $ingredient->units === 'ml'
// $ingredient->name === 'lime juice'
// $ingredient->comment === 'freshly squeezed'

// Available via static call
$ingredient = Parser::line('30 ml Tequila reposado (preferebly Patron)');

// Add custom units
$ingredientParser->setUnitParser(
    new UnitParser([
        'test' => ['lorem', 'ipsum']
    ])
);

$ingredient = $ingredientParser->parseLine('15 lorem ingredient names');
// Output:
// $ingredient->units === 'test'

Unit converter usage

Simple unit conversion implemented with enums. Not made for accuracy. Handles mostly cocktail recipe units (ml, oz, cl, dash...). Can handle fractional display amounts (¾, 1 1/2..).

<?php

declare(strict_types=1);

use Kami\RecipeUtils\Converter;
use Kami\RecipeUtils\UnitConverter\Oz;
use Kami\RecipeUtils\UnitConverter\Units;
use Kami\RecipeUtils\UnitConverter\AmountValue;

// Via converter service
$ingredientToConvert = new RecipeIngredient(
    name: 'Vodka',
    amount: '1 1/2',
    units: 'oz',
);

$convertedIngredient = Converter::tryConvert($ingredientToConvert, Units::Ml);
var_dump($convertedIngredient);
// Output:
// $ingredient->amount === 45.0
// $ingredient->units === 'ml'
// $ingredient->name === 'Vodka'

// Via specific units
$amountValue = AmountValue::fromString('1 1/2');
var_dump((new Oz($amountValue))->toMl()->getValue());
// Output:
// float: 45.0