-
Notifications
You must be signed in to change notification settings - Fork 4
/
StoryRenderer.php
205 lines (194 loc) · 6.46 KB
/
StoryRenderer.php
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
<?php
namespace TwigStorybook\Service;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use TwigStorybook\Exception\StoryRenderException;
use TwigStorybook\Exception\StorySyntaxException;
use TwigStorybook\Story;
/**
* Render a component with some context.
*/
final class StoryRenderer
{
/**
* The twig environment.
*
* @var \Twig\Environment|null
*/
private ?Environment $environment = null;
/**
* Creates a new ComponentRenderer.
*/
public function __construct(
private readonly StoryCollector $storyCollector,
private readonly LoggerInterface $logger,
private readonly string $root,
) {
}
/**
* Renders the Twig markup of a component.
*
* @param string $story_id
* @param array $story_meta
* @param string $story_template
* @param array $context
* The context of the component.
*
* @return string
* The rendered markup.
* @throws \TwigStorybook\Exception\StoryRenderException
*/
public function renderStory(string $hash, Request $request): string
{
try {
$decoded = json_decode(
base64_decode(urldecode($hash)),
true,
512,
JSON_THROW_ON_ERROR,
);
} catch (\JsonException $e) {
throw new StoryRenderException(
'Unable to decode the story ID. Avoid tampering with the generated URL.',
previous: $e
);
}
$template_path = $decoded['path'] ?? '';
$story_id = $decoded['id'] ?? '';
if (empty($template_path) || empty($story_id)) {
throw new StoryRenderException(
'Impossible to locate a story to render without the template path or the story name.'
);
}
if (!$this->environment instanceof Environment) {
return '';
}
// Merge into the $context, the values for the args from the HTTP request originated in Storybook.
$context = [
...$this->getArguments($request, $template_path, $story_id),
'_story' => $story_id,
];
try {
return $this->environment->load($template_path)->render($context);
} catch (LoaderError | SyntaxError | RuntimeError $exception) {
$this->logger->error($exception->getMessage());
return '';
}
}
/**
* Gets the arguments.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The inbound request.
* @param string $template_path
* @param string $story_id
*
* @return array
* The array of arguments.
* @throws \Twig\Error\LoaderError
* @throws \Twig\Error\RuntimeError
* @throws \Twig\Error\SyntaxError
*/
private function getArguments(Request $request, string $template_path, string $story_id): array
{
$wrapper = $this->environment->load($template_path);
$wrapper->render(['_story' => false]);
$stories = $this->storyCollector->getAllStories($template_path);
// Generate the story based on the path and ID. We need to inspect the args.
$filtered = array_filter(
$stories,
static fn(Story $st) => $st->id === $story_id,
);
$story = reset($filtered);
if (empty($story)) {
$message = sprintf('Impossible to find the story with ID "%s" in "%s".', $story_id, $template_path);
throw new NotFoundHttpException($message);
}
$arg_names = array_keys($story->meta['args'] ?? []);
return array_map(
static function (string $value) {
try {
return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return $value;
}
},
array_intersect_key(
$request->query->getIterator()->getArrayCopy(),
array_flip($arg_names),
)
);
}
public function generateStoriesJsonFile(string $stories_path, string $url = '')
{
// Trigger the compilation of the template to collect the stories.
$wrapper = $this->environment->load($stories_path);
// This will execute the `compile` method without rendering anything.
$wrapper->render(['_story' => false]);
$path = ltrim(
str_replace(
$this->root,
'',
$wrapper->getSourceContext()->getPath(),
),
'/'
);
$wrapper_data = $this->storyCollector->getWrapperData($path);
if (!empty($url)) {
$wrapper_data['parameters']['server']['url'] = $url;
}
$stories = array_map(
fn(Story $story) => $this->massageStory($story, $path, $url),
$this->storyCollector->getAllStories($path),
);
return [
...$wrapper_data,
'stories' => $stories,
];
}
/**
* @throws \TwigStorybook\Exception\StorySyntaxException
* @throws \JsonException
*/
private function massageStory(Story $story, string $stories_path): array
{
$meta = $story->meta;
if ($meta['parameters']['server']['id'] ?? null) {
$message = 'The parameters.server.id property for a story will be ';
$message .= 'generated automatically. Do not provide it.';
throw new StorySyntaxException($message);
}
// This ID will be used by Storybook to call the server. Something like:
// "https://example.com/$id"
$meta['parameters']['server']['id'] = urlencode(base64_encode(
json_encode(
[
'path' => $stories_path,
'id' => $story->id,
],
JSON_THROW_ON_ERROR
)
));
$name = $meta['name'] ?? $story->id;
$meta['name'] = $name;
return $meta;
}
private function validateStory(array $story)
{
}
/**
* Sets the Twig environment.
*
* @param \Twig\Environment $environment
* The environment.
*/
public function setTwigEnvironment(Environment $environment): void
{
$this->environment = $environment;
}
}