aboutsummaryrefslogtreecommitdiff
path: root/lib/exTpl/Context.php
diff options
context:
space:
mode:
authorPhilipp Schüttlöffel <schuettloeffel@zqs.uni-hannover.de>2024-09-24 10:53:31 +0200
committerPhilipp Schüttlöffel <schuettloeffel@zqs.uni-hannover.de>2024-09-24 10:53:31 +0200
commit4459dd7917f4d1c34f40bb68f0e991e9c3d53e4c (patch)
tree5c07151ae61276d334e88f6309c30d439a85c12e /lib/exTpl/Context.php
parentda0022e5c1abbf9825ae76debaabdff7e8623bb4 (diff)
parent97a188592c679890a25c37ab78463add76a52ff7 (diff)
Merge branch 'main' into issue-3911issue-3911
Diffstat (limited to 'lib/exTpl/Context.php')
-rw-r--r--lib/exTpl/Context.php77
1 files changed, 77 insertions, 0 deletions
diff --git a/lib/exTpl/Context.php b/lib/exTpl/Context.php
new file mode 100644
index 0000000..309174f
--- /dev/null
+++ b/lib/exTpl/Context.php
@@ -0,0 +1,77 @@
+<?php
+/**
+ * Context.php - template parser symbol table
+ *
+ * A Context object represents the symbol table used to resolve
+ * symbol names to their values in the local scope. Each context
+ * may inherit symbol definitions from its parent context.
+ *
+ * @copyright 2013 Elmar Ludwig
+ * @license GPL2 or any later version
+ */
+
+namespace exTpl;
+
+use Closure;
+
+class Context
+{
+ private array $bindings;
+ private Closure|null $escape;
+ private Context|null $parent;
+
+ /**
+ * Initializes a new Context instance with the given bindings.
+ *
+ * @param array $bindings symbol table
+ * @param Context|null $parent parent context (or NULL)
+ */
+ public function __construct(array $bindings, Context $parent = null)
+ {
+ $this->bindings = $bindings;
+ $this->parent = $parent;
+ }
+
+ /**
+ * Looks up the value of a symbol in this context and returns it.
+ * The reserved symbol "this" is an alias for the current context.
+ *
+ * @param string $key symbol name
+ */
+ public function lookup(string $key): mixed
+ {
+ if (isset($this->bindings[$key])) {
+ return $this->bindings[$key];
+ } else if ($this->parent) {
+ return $this->parent->lookup($key);
+ }
+
+ return null;
+ }
+
+ /**
+ * Enables or disables automatic escaping for template values.
+ *
+ * @param callable|null $escape escape callback or null
+ */
+ public function autoescape(?callable $escape): void
+ {
+ $this->escape = $escape ? $escape(...) : null;
+ }
+
+ /**
+ * Escapes the given value using the configured strategy.
+ *
+ * @param mixed $value expression value
+ */
+ public function escape(mixed $value): mixed
+ {
+ if (isset($this->escape)) {
+ $value = call_user_func($this->escape, $value);
+ } else if ($this->parent) {
+ $value = $this->parent->escape($value);
+ }
+
+ return $value;
+ }
+}