php-juicer/src/Recipe/Importer/JsonImporter.php

58 lines
1.4 KiB
PHP

<?php
namespace NoccyLabs\Juicer\Recipe\Importer;
use NoccyLabs\Juicer\Recipe\RecipeInterface;
use NoccyLabs\Juicer\Recipe\Recipe;
use NoccyLabs\Juicer\Ingredient\Ingredient;
/**
* Import recipes from Json
*
*/
class JsonImporter
{
/**
* Import a recipe from json
*
* @param string The json string to parse and import
* @return RecipeInterface
*/
public function import(string $json): RecipeInterface
{
$data = json_decode($json);
$recipe = new Recipe();
$recipe->setRecipeName(@$data->recipe);
$recipe->setRecipeAuthor(@$data->author);
$recipe->setDescription(@$data->description);
$recipe->setExtra((array)@$data->extra);
foreach ((array)@$data->ingredients as $ingredientData) {
$ingredient = new Ingredient($ingredientData->flavor, $ingredientData->brand, $ingredientData->percent);
$recipe->addIngredient($ingredient);
}
return $recipe;
}
/**
* Import a recipe from json contained in a file
*
* @param string The filename to read and import
* @return RecipeInterface
*/
public function readFromFile(string $filename): RecipeInterface
{
$fd = fopen($filename, "r");
if (!$fd) {
throw new \InvalidArgumentException();
}
$json = fread($fd, filesize($filename));
fclose($fd);
return $this->import($json);
}
}