php-juicer/src/Recipe/Importer/XmlImporter.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 XML
*
*/
class XmlImporter implements ImporterInterface
{
/**
* Import a recipe from xml
*
* @param string The xml string to parse and import
* @return RecipeInterface
*/
public function import(string $xml): RecipeInterface
{
$data = simplexml_parse_string($xml);
$recipe = new Recipe();
$recipe->setRecipeName((string)$data->recipe);
$recipe->setRecipeAuthor((string)$data->author);
$recipe->setDescription((string)$data->description);
foreach ((array)@$data->ingredients->ingredient 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();
}
$xml = fread($fd, filesize($filename));
fclose($fd);
return $this->import($xml);
}
}