php-juicer/src/Recipe/Exporter/JsonExporter.php

49 lines
1.3 KiB
PHP

<?php
namespace NoccyLabs\Juicer\Recipe\Exporter;
use NoccyLabs\Juicer\Recipe\RecipeInterface;
use NoccyLabs\Juicer\Ingredient\IngredientInterface;
class JsonExporter
{
public function export(RecipeInterface $recipe)
{
$ingredients = [];
/** @var IngredientInterface $ingredient */
foreach ($recipe->getIngredients() as $ingredient) {
$ingredients[] = [
'brand' => $ingredient->getFlavorBrand(),
'flavor' => $ingredient->getFlavorName(),
'percent' => $ingredient->getPercent()
];
}
$document = [
'recipe' => $recipe->getRecipeName(),
'author' => $recipe->getRecipeAuthor(),
'tags' => $recipe->getTags(),
'description' => $recipe->getDescription(),
'extra' => $recipe->getExtra(),
'ingredients' => $ingredients
];
return json_encode($document,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES);
}
public function writeToFile(RecipeInterface $recipe, string $filename)
{
$json = $this->export($recipe);
$fd = fopen($filename, "w");
if (!$fd) {
throw new \InvalidArgumentException();
}
fwrite($fd, $json, strlen($json));
fclose($fd);
}
}