2019-07-07 23:13:30 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace NoccyLabs\Juicer\Recipe\Importer;
|
|
|
|
|
|
|
|
use NoccyLabs\Juicer\Recipe\RecipeInterface;
|
|
|
|
use NoccyLabs\Juicer\Recipe\Recipe;
|
|
|
|
use NoccyLabs\Juicer\Ingredient\Ingredient;
|
|
|
|
|
2019-07-09 00:10:56 +00:00
|
|
|
/**
|
|
|
|
* Import recipes from Json
|
|
|
|
*
|
|
|
|
*/
|
2021-03-01 13:41:21 +00:00
|
|
|
class JsonImporter implements ImporterInterface
|
2019-07-07 23:13:30 +00:00
|
|
|
{
|
|
|
|
|
2019-07-09 00:10:56 +00:00
|
|
|
/**
|
|
|
|
* Import a recipe from json
|
|
|
|
*
|
|
|
|
* @param string The json string to parse and import
|
|
|
|
* @return RecipeInterface
|
|
|
|
*/
|
2019-07-07 23:13:30 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2019-07-09 00:10:56 +00:00
|
|
|
/**
|
|
|
|
* Import a recipe from json contained in a file
|
|
|
|
*
|
|
|
|
* @param string The filename to read and import
|
|
|
|
* @return RecipeInterface
|
|
|
|
*/
|
2019-07-07 23:13:30 +00:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
2021-03-01 13:41:21 +00:00
|
|
|
}
|