-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathSchema.php
More file actions
78 lines (65 loc) · 2.36 KB
/
Schema.php
File metadata and controls
78 lines (65 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
declare(strict_types=1);
namespace Kami\Cocktail\External\Model;
use Symfony\Component\Yaml\Yaml;
use Spatie\ArrayToXml\ArrayToXml;
use Kami\Cocktail\External\SupportsXML;
use Kami\Cocktail\External\SupportsYAML;
use Kami\RecipeUtils\UnitConverter\Units;
use Kami\Cocktail\External\SupportsDraft2;
use Kami\Cocktail\External\SupportsMarkdown;
use Kami\Cocktail\Models\Cocktail as CocktailModel;
readonly class Schema implements SupportsDraft2, SupportsXML, SupportsMarkdown, SupportsYAML
{
public const SCHEMA_VERSION = 'draft2';
public const SCHEMA_URL = 'https://barassistant.app/cocktail-02.schema.json';
/**
* @param array<Ingredient> $ingredients
*/
public function __construct(
public Cocktail $cocktail,
public array $ingredients,
) {
}
public static function fromCocktailModel(CocktailModel $model, ?Units $toUnits = null): self
{
$ingredients = [];
foreach ($model->ingredients as $cocktailIngredient) {
$ingredients[] = Ingredient::fromModel($cocktailIngredient->ingredient);
foreach ($cocktailIngredient->substitutes as $substitute) {
$ingredients[] = Ingredient::fromModel($substitute->ingredient);
}
}
return new self(
Cocktail::fromModel($model, toUnits: $toUnits),
$ingredients,
);
}
public static function fromDraft2Array(array $source): self
{
return new self(
Cocktail::fromDraft2Array($source['recipe']),
array_map(Ingredient::fromDraft2Array(...), $source['ingredients']),
);
}
public function toDraft2Array(): array
{
return [
'recipe' => $this->cocktail->toDraft2Array(),
'ingredients' => array_map(fn ($model) => $model->toDraft2Array(), $this->ingredients),
];
}
public function toXML(): string
{
return ArrayToXml::convert($this->toDraft2Array(), self::SCHEMA_VERSION, domProperties: ['preserveWhiteSpace' => true, 'formatOutput' => true], xmlEncoding: 'UTF-8');
}
public function toMarkdown(): string
{
$cocktail = $this->cocktail;
return view('md_recipe_template', compact('cocktail'))->render();
}
public function toYAML(): string
{
return Yaml::dump($this->toDraft2Array(), 4, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
}
}