-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRenderContext.php
More file actions
403 lines (329 loc) · 11.2 KB
/
RenderContext.php
File metadata and controls
403 lines (329 loc) · 11.2 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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<?php
namespace Keepsuit\Liquid\Render;
use ArithmeticError;
use Closure;
use Keepsuit\Liquid\Contracts\CanBeEvaluated;
use Keepsuit\Liquid\Contracts\IsContextAware;
use Keepsuit\Liquid\Contracts\LiquidErrorHandler;
use Keepsuit\Liquid\Contracts\MapsToLiquid;
use Keepsuit\Liquid\Drop;
use Keepsuit\Liquid\Environment;
use Keepsuit\Liquid\ErrorHandlers\RethrowErrorHandler;
use Keepsuit\Liquid\Exceptions\ArithmeticException;
use Keepsuit\Liquid\Exceptions\InternalException;
use Keepsuit\Liquid\Exceptions\LiquidException;
use Keepsuit\Liquid\Exceptions\ResourceLimitException;
use Keepsuit\Liquid\Exceptions\StackLevelException;
use Keepsuit\Liquid\Exceptions\StandardException;
use Keepsuit\Liquid\Exceptions\UndefinedDropMethodException;
use Keepsuit\Liquid\Interrupts\Interrupt;
use Keepsuit\Liquid\Nodes\VariableLookup;
use Keepsuit\Liquid\Parse\ParseContext;
use Keepsuit\Liquid\Support\Arr;
use Keepsuit\Liquid\Support\MissingValue;
use Keepsuit\Liquid\Support\OutputsBag;
use Keepsuit\Liquid\Template;
use RuntimeException;
use Throwable;
final class RenderContext
{
public readonly Environment $environment;
public readonly ResourceLimits $resourceLimits;
protected LiquidErrorHandler $errorHandler;
protected int $baseScopeDepth = 0;
protected ?string $templateName = null;
public bool $partial = false;
/**
* @var array<array<string, mixed>>
*/
protected array $scopes;
protected ContextSharedState $sharedState;
/**
* @var array<string, mixed>
*/
protected array $dynamicRegisters = [];
/**
* @var array<Interrupt>
*/
protected array $interrupts = [];
public function __construct(
/**
* Environment variables only available in the current context
*
* @var array<string, mixed>
*/
protected array $data = [],
/**
* Environment variables that are shared with all sub-contexts
*
* @var array<string, mixed> $staticEnvironment
*/
array $staticData = [],
/**
* Registers allows to provide/export data or utilities inside tags
* Registers are not accessible as variables.
* Registers are shared with all sub-contexts
*
* @var array<string, mixed> $registers
*/
array $registers = [],
public readonly RenderContextOptions $options = new RenderContextOptions,
?ResourceLimits $resourceLimits = null,
?Environment $environment = null,
) {
$this->environment = $environment ?? Environment::default();
$this->resourceLimits = $resourceLimits ?? ResourceLimits::clone($this->environment->defaultResourceLimits);
$this->errorHandler = $this->options->rethrowErrors ? new RethrowErrorHandler : $this->environment->errorHandler;
$this->scopes = [[]];
$this->sharedState = new ContextSharedState(
staticVariables: $staticData,
registers: array_merge($this->environment->getRegisters(), $registers),
);
}
public function isPartial(): bool
{
return $this->partial;
}
protected function push(array $newScope = []): void
{
array_unshift($this->scopes, $newScope);
$this->checkOverflow();
}
protected function pop(): array
{
if (count($this->scopes) === 1) {
throw new RuntimeException('Cannot pop the outer scope');
}
return array_shift($this->scopes) ?? [];
}
/**
* @template TResult
*
* @param Closure(RenderContext $context): TResult $closure
* @return TResult
*/
public function stack(Closure $closure)
{
$this->push();
try {
$result = $closure($this);
} finally {
$this->pop();
}
return $result;
}
public function evaluate(mixed $value): mixed
{
if ($value instanceof CanBeEvaluated) {
return $this->evaluate($value->evaluate($this));
}
return $value;
}
/**
* @param array<string,mixed> $values
*/
public function merge(array $values): void
{
$this->scopes[0] = [
...$this->scopes[0],
...$values,
];
}
public function set(string $key, mixed $value): void
{
Arr::set($this->scopes[0], $key, $value);
}
public function get(string $key): mixed
{
return $this->evaluate(VariableLookup::fromMarkup($key));
}
public function has(string $key): bool
{
return $this->get($key) !== null;
}
public function findVariables(string $key): array
{
$variables = [];
foreach ($this->scopes as $scope) {
$variables[] = $this->internalContextLookup($scope, $key);
}
$variables[] = $this->internalContextLookup($this->data, $key);
$variables[] = $this->internalContextLookup($this->sharedState->staticVariables, $key);
$variables = array_values(array_filter($variables, fn (mixed $value) => ! $value instanceof MissingValue));
foreach ($variables as $variable) {
if ($variable instanceof IsContextAware) {
$variable->setContext($this);
}
}
return $variables;
}
public function internalContextLookup(mixed $scope, int|string $key): mixed
{
try {
$value = match (true) {
is_array($scope) && array_key_exists($key, $scope) => $scope[$key],
$scope instanceof Drop => $scope->{$key},
is_object($scope) && property_exists($scope, (string) $key) => $scope->{$key},
default => new MissingValue,
};
} catch (UndefinedDropMethodException) {
return new MissingValue;
}
return $this->normalizeValue($value);
}
public function normalizeValue(mixed $value): mixed
{
if (is_object($value) && isset($this->sharedState->computedObjectsCache[$value])) {
return $this->sharedState->computedObjectsCache[$value];
}
if ($value instanceof Closure) {
return $this->sharedState->computedObjectsCache[$value] ??= $this->normalizeValue($value($this));
}
if ($value instanceof MapsToLiquid) {
$liquidValue = $value->toLiquid();
// Check if toLiquid() returns itself
return $this->sharedState->computedObjectsCache[$value] ??= match (true) {
$value === $liquidValue => $value,
default => $this->normalizeValue($liquidValue)
};
}
return $value;
}
public function applyFilter(string $filter, mixed $value, array $args = []): mixed
{
return $this->environment->filterRegistry->invoke($this, $filter, $value, $args);
}
public function getRegister(string $name): mixed
{
return $this->dynamicRegisters[$name] ?? $this->sharedState->registers[$name] ?? null;
}
public function setRegister(string $name, mixed $value): void
{
$this->dynamicRegisters[$name] = $value;
}
public function getData(string $name): mixed
{
return $this->data[$name] ?? null;
}
public function setData(string $name, mixed $value): mixed
{
return $this->data[$name] = $value;
}
public function setToActiveScope(string $key, mixed $value): array
{
$index = array_key_last($this->scopes);
return $this->scopes[$index] = [
...$this->scopes[$index],
$key => $value,
];
}
public function pushInterrupt(Interrupt $interrupt): void
{
$this->interrupts[] = $interrupt;
}
public function popInterrupt(): ?Interrupt
{
return array_pop($this->interrupts);
}
public function hasInterrupt(): bool
{
return count($this->interrupts) > 0;
}
/**
* @throws LiquidException
*/
public function handleError(Throwable $error, ?int $lineNumber = null): string
{
$error = match (true) {
$error instanceof ResourceLimitException => throw $error,
$error instanceof ArithmeticError => new ArithmeticException($error),
$error instanceof LiquidException => $error,
default => new InternalException($error),
};
$error->lineNumber = $error->lineNumber ?? $lineNumber;
$error->templateName = $error->templateName ?? $this->templateName;
$this->sharedState->errors[] = $error;
return $this->errorHandler->handle($error);
}
public function getErrors(): array
{
return $this->sharedState->errors;
}
public function getTemplateName(): ?string
{
return $this->templateName;
}
public function loadPartial(string $templateName): Template
{
if ($partial = $this->environment->templatesCache->get($templateName)) {
return $partial;
}
if ($this->options->lazyParsing === false) {
throw new StandardException(sprintf("The partial '%s' has not be loaded during parsing", $templateName));
}
$parseContext = $this->environment->newParseContext();
$template = $parseContext->loadPartial($templateName);
$this->sharedState->outputs->merge($template->state->outputs);
return $template;
}
public function mergeOutputs(OutputsBag $outputs): RenderContext
{
$this->sharedState->outputs->merge($outputs);
return $this;
}
public function getOutputs(): OutputsBag
{
return $this->sharedState->outputs;
}
/**
* @throws StackLevelException
*/
public function newIsolatedSubContext(?string $templateName = null, ?RenderContextOptions $options = null): RenderContext
{
$this->checkOverflow();
$subContext = new RenderContext(
options: $options ?? $this->options,
resourceLimits: $this->resourceLimits,
environment: $this->environment,
);
$subContext->baseScopeDepth = $this->baseScopeDepth + 1;
$subContext->sharedState = $this->sharedState;
$subContext->templateName = $templateName;
$subContext->partial = true;
return $subContext;
}
/**
* @template TResult
*
* @param string[] $tags
* @param Closure(RenderContext $context): TResult $closure
* @return TResult
*/
public function withDisabledTags(array $tags, Closure $closure)
{
foreach ($tags as $tag) {
$this->sharedState->disabledTags[$tag] = ($this->sharedState->disabledTags[$tag] ?? 0) + 1;
}
try {
$output = $closure($this);
} finally {
foreach ($tags as $tag) {
$this->sharedState->disabledTags[$tag] = max(0, ($this->sharedState->disabledTags[$tag] ?? 0) - 1);
}
}
return $output;
}
public function tagDisabled(string $tag): bool
{
return ($this->sharedState->disabledTags[$tag] ?? 0) > 0;
}
/**
* @throws StackLevelException
*/
protected function checkOverflow(): void
{
if ($this->baseScopeDepth + count($this->scopes) > ParseContext::MAX_DEPTH) {
throw StackLevelException::nestingTooDeep();
}
}
}