Updated importers, exporters, PHP 8.x

This commit is contained in:
2021-03-01 14:41:21 +01:00
parent efe875bd05
commit 104856f425
8 changed files with 200 additions and 6 deletions

View File

@ -0,0 +1,45 @@
<?php
namespace NoccyLabs\Juicer\Ingredient\Importer;
use NoccyLabs\Juicer\Ingredient\Ingredient;
use NoccyLabs\Juicer\Ingredient\IngredientInterface;
class JsonImporter
{
/**
* Import ingredient from json
*
* @param string The json string to parse and import
* @return IngredientInterface
*/
public function import(string $json): IngredientInterface
{
$data = json_decode($json);
$ingredient = new Ingredient($data->flavoringName, $data->brandKey);
print_r($data);
return $ingredient;
}
/**
* Import ingredient from json contained in a file
*
* @param string The filename to read and import
* @return IngredientInterface
*/
public function readFromFile(string $filename): IngredientInterface
{
$fd = fopen($filename, "r");
if (!$fd) {
throw new \InvalidArgumentException();
}
$json = fread($fd, filesize($filename));
fclose($fd);
return $this->import($json);
}
}

View File

View File

@ -0,0 +1,15 @@
<?php
namespace NoccyLabs\Juicer\Recipe\Importer;
use NoccyLabs\Juicer\Recipe\RecipeInterface;
interface ImporterInterface
{
public function readFromFile(string $filename): RecipeInterface;
public function import(string $data): RecipeInterface;
}

View File

@ -10,7 +10,7 @@ use NoccyLabs\Juicer\Ingredient\Ingredient;
* Import recipes from Json
*
*/
class JsonImporter
class JsonImporter implements ImporterInterface
{
/**
@ -55,4 +55,4 @@ class JsonImporter
return $this->import($json);
}
}
}

View File

@ -0,0 +1,57 @@
<?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);
}
}