Search by

hryvinskyi / magento2-json-template

hryvinskyi

Compiled JSON templates for Magento 2: a JSON document with {{ expressions }}, filters and directive keys, compiled once to an immutable tree and evaluated against a variable scope

Package info

github.com/hryvinskyi/magento2-json-template

Type:magento2-module

pkg:composer/hryvinskyi/magento2-json-template

Statistics

Installs: 2

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-11-22 19:24 UTC

This package is auto-updated.

Last update: 2026-11-22 19:38:14 UTC


README

Compiled JSON templates for Magento 2. A template is a JSON document. Its strings can hold {{ expressions }}. Its objects can hold directive keys (@if, @each, @as, @limit, @value, @include). The compiler turns a template into an immutable syntax tree of plain arrays, and the cache keeps that tree as JSON. The evaluator turns the tree into closures once per process. It then runs the closures against a scope of variables and returns the JSON value with every empty part pruned.

{
  "@type": "Product",
  "name": "{{ product.name }}",
  "description": "{{ product.short_description | plain | limit:5000 }}",
  "image": { "@each": "product.gallery", "@as": "image", "@value": "{{ image.url | url }}" },
  "priceValidUntil": { "@if": "product.on_sale", "@value": "{{ product.special_to_date | date:'Y-m-d' }}" }
}

With a product that is on sale, this template evaluates to:

{"@type":"Product","name":"Satchel","description":"Leather bag","image":["/a.jpg","/b.jpg"],"priceValidUntil":"2026-12-31"}

Requirements

  • Magento 2 with PHP 8.2 to 8.5, ext-intl (the slug filter) and ext-mbstring.
  • The package declares only magento/framework and psr/log.

Installation

composer require hryvinskyi/magento2-json-template
bin/magento setup:upgrade
bin/magento setup:di:compile

setup:upgrade enables the JSON Templates cache type (json_template) on an existing store. A fresh installation enables it with every other cache type.

Using the engine

Hryvinskyi\JsonTemplate\Api\TemplateEngineInterface is the entry point most code needs. Inject it with the scope factory:

use Hryvinskyi\JsonTemplate\Api\JsonEncoderInterface;
use Hryvinskyi\JsonTemplate\Api\ScopeFactoryInterface;
use Hryvinskyi\JsonTemplate\Api\TemplateEngineInterface;

class ProductSnippet
{
    public function __construct(
        private readonly TemplateEngineInterface $engine,
        private readonly ScopeFactoryInterface $scopes
    ) {
    }

    public function write(string $source, array $product): ?string
    {
        $scope = $this->scopes->create(['product' => $product]);

        return $this->engine->render($source, $scope, JsonEncoderInterface::HTML_SCRIPT_FLAGS);
    }
}
  • compile($source) returns the compiled form from the compiled-template storage. If the storage has none, it compiles the source and stores the result. A template that does not compile throws CompileException with every error at once.
  • evaluate($source, $scope, $trace = null) compiles through the storage, evaluates, and returns the pruned value, or null when nothing is left.
  • render($source, $scope, $flags) evaluates and writes the value as JSON with the json_encode() flags you pass. The engine chooses no flags of its own. It returns null when nothing is left.
  • CompilerInterface::compile() takes JSON text or a decoded array and does not use the storage. EvaluatorInterface::evaluate() takes a compiled template, a scope and an optional trace.

A compile error. CompileException::getErrors() lists CompileErrorInterface objects. Each one has a JSON path ($.offers[2].price, or $['http://schema.org/name'] for a key that is not a plain name), a message code, parameters and, inside a string, an offset in Unicode code points. The package never words a message. The code that shows the error does. See Compile errors for the codes.

JSON inside HTML. JsonEncoderInterface::forHtmlScript($value, $pretty) writes JSON for the body of a <script> element. It uses JSON_HEX_TAG | JSON_HEX_AMP | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR, and JSON_PRETTY_PRINT when $pretty is true. No text in the value can end the element: </script> becomes </script>. The same flags are the constant JsonEncoderInterface::HTML_SCRIPT_FLAGS. An encoding failure always throws \JsonException.

Text from outside. Api\TemplateLiteralsInterface writes outside text into a template so the language reads it back unchanged. Code that builds a template from a shop name or a link never escapes by hand.

  • expressionString($text) returns a single-quoted string literal for an expression. It puts a backslash before each backslash and single quote.
  • text($text) returns template-string text with no expression in it. It writes every {{ as {{{{. The result may be a whole string or may follow an expression. Text that ends in { cannot stand directly before an expression, because the language has no escape for one brace.
$template = json_encode([
    'brand' => '{{ product.brand | default:' . $this->literals->expressionString("O'Hara") . ' }}',
    'note' => $this->literals->text('Order {{ now }}'),
], JSON_UNESCAPED_SLASHES);
// {"brand":"{{ product.brand | default:'O\\'Hara' }}","note":"Order {{{{ now }}"}

Build the JSON with json_encode(), as above. The expression literal contains a backslash, and JSON needs that backslash escaped again. Evaluating this template with no product gives {"brand":"O'Hara","note":"Order {{ now }}"}. Any text round-trips: quotes, backslashes, }}, |, {{ and multibyte characters. Test/_vectors/literals.json pins the escapes.

A compiled tree. CompiledTemplateInterface::getAst() returns a tree of plain arrays. Each node holds its kind under AstNodeKind::KEY (kind). The constants of Api\Data\AstNodeKind name the kinds and say which keys each kind has. Template nodes are literal, interp, text, object, list, directive and include. Expression nodes are path, lit, not, and, or, cmp and filter. Code that walks a tree, or keys a pool by node kind, uses these constants and never writes the strings again. (In a di.xml pool the string is the item name.)

$compiled = $this->engine->compile('{"a":"{{ p.name | upper }}","b":1}');
// $compiled->getAst() is
// {"kind":"object","entries":[
//   ["a",{"kind":"interp","expression":{"kind":"filter","name":"upper",
//         "input":{"kind":"path","segments":["p","name"]},"arguments":[]}}],
//   ["b",{"kind":"literal","value":1}]]}

getRoots() and getPaths() list what a template reads. getIncludes() lists the codes it includes. getSourceHash() is the hash of the source.

The language

Grammar

string       = { text | "{{{{" | "{{" , expression , "}}" } ;
                 (* "{{{{" is a literal "{{"; a "}}" outside an expression is plain text *)

expression   = or ;
or           = and , { ( "||" | "or" ) , and } ;
and          = not , { ( "&&" | "and" ) , not } ;
not          = ( "!" | "not" ) , not | comparison ;
comparison   = filtered , [ comparator , filtered ] ;
comparator   = "==" | "!=" | ">=" | "<=" | ">" | "<" ;
filtered     = primary , { "|" , name , [ ":" , argument , { "," , argument } ] } ;
argument     = path | literal ;
primary      = path | literal | "(" , expression , ")" ;
literal      = quoted | number | "true" | "false" | "null" ;
path         = name , { "." , ( name | integer ) } ;
name         = ( letter | "_" ) , { letter | digit | "_" } ;     (* ASCII only *)
integer      = digit , { digit } ;
number       = [ "-" ] , digit , { digit } , [ "." , digit , { digit } ] ;
quoted       = "'" , { character | "\" , character } , "'"
             | '"' , { character | "\" , character } , '"' ;
  • A filter binds tighter than a comparison. A comparison binds tighter than not, then and, then or. A comparison cannot chain: a < b < c is a compile error.
  • and, or, not, true, false and null are keywords only where a path cannot continue. product.not is a path.
  • A backslash in a quoted string takes the next character as it is. Quotes protect }}, |, : and ,: none of them ends anything inside a quoted string.
  • A number has at most 18 integer digits. A number cannot start with ..
  • A string that is exactly one {{ expression }} yields the typed value of the expression. A string that mixes text and expressions yields a string. That string is empty if any of its expressions is empty.
  • {{ }} (nothing inside) and a {{ that never closes are compile errors.
  • The value of @if and @each is a bare expression ("@if": "product.on_sale"). Braces there are a compile error.

Values

  • Scope. ScopeFactoryInterface::create(array $variables) makes the scope of one evaluation. A root (product in product.name) comes from a local frame first (a repeated item, loop). Then it comes from the variables you gave. Then it comes from the variable provider registered for that root, which the scope asks at most once. A path walks arrays and Api\Data\ValueInterface values only, never other objects. A root that nothing supplies is empty. A scope holds state: create one per evaluation.
  • Empty is null, '', an empty list, and an object that has only @type and @context left. An empty value drops its key or its list slot. A container with nothing left is empty in turn. false, 0 and '0' are not empty: the output keeps them.
  • Truthy is anything that is not empty and not false, 0 or '0'. and, or and not yield booleans. and and or do not evaluate the right side once the left side decides.
  • Comparison. Two numeric values (numbers, or numeric strings with no surrounding whitespace) compare as numbers, so '1' == 1. Anything else compares strictly by type, so '1' == true is false. Two strings order byte by byte.
  • Numbers. Integers stay integers. Floats stay floats. json_encode() writes the float 4.0 as 4, unless you pass JSON_PRESERVE_ZERO_FRACTION.
  • A variable's text is data. The engine never reads a value as a template: a variable that holds {{ secret }} comes out as the text {{ secret }}.

Directives

A key that starts with @ is a directive when a directive compiler is registered under its name. Any other @ key (@type, @context, @id, @graph) is plain JSON-LD and passes through.

Directive Value Meaning
@if expression Without @each, the object stays only when the expression is truthy. The trace reports it as skipped otherwise. With @each, it filters each item.
@each expression The object becomes a list with one item per element of the list the expression yields.
@as name The name that reads each item. It needs @each. It is an ASCII identifier and cannot be and, or, not, true, false, null or loop. Default: the host's name for the collection (ItemAliasResolverInterface), else item.
@limit positive integer The most items @each keeps. It needs @each.
@value template The object evaluates to this value instead of to its keys. A scalar can then carry @if or @each.
@include code The object evaluates to the template that the host resolves for the code (IncludeResolverInterface). The code is a fixed string.

Combination rules:

  • In one object, @each comes first. Then, for each item, in the item's frame, the engine evaluates @if (a filter on the items, not a guard on the list), then @value or the object's keys, then prunes. @limit counts the items kept, so "the newest 3" never gives 2 because one item was empty. After @limit items the engine stops evaluating the rest. loop.index (from 1), loop.first, loop.last and loop.length describe the source list before filtering.
  • Without @each, @if guards the object. @if with @value makes a conditional scalar.
  • @value with any sibling other than @if, @each, @as and @limit is a compile error.
  • @include accepts only @if beside it. There is no merging. The included template is evaluated in the includer's scope, so loop variables are visible. It loses its root @context. A code with no template is empty, traced (include-missing) and logged once per request. An include of a code that is already being evaluated is empty. So is an include nested deeper than 8 levels.
  • An @each object inside an array literal splices its items into that array. Anywhere else it becomes a list. @each over an empty value is empty. @each over a value that is not a list is empty and traced (not-a-list).
{
  "review": {
    "@each": "reviews",
    "@as": "r",
    "@if": "r.rating >= 4",
    "@limit": 2,
    "@type": "Review",
    "reviewBody": "{{ r.text }}",
    "position": "{{ loop.index }}"
  },
  "image": ["/cover.jpg", { "@each": "product.gallery", "@as": "i", "@value": "{{ i.url }}" }]
}

With five reviews, of which the second and third are below four stars, and a two-image gallery, this evaluates to:

{"review":[{"@type":"Review","reviewBody":"Ages well","position":1},{"@type":"Review","reviewBody":"Roomy","position":4}],"image":["/cover.jpg","/a.jpg","/b.jpg"]}

The review list shows position 4 for the second kept item. loop.index counts the source list. The gallery items join the array literal at the same level.

Filters

A filter is a named, pure transformation: {{ value | name:argument,argument }}. The compiler checks the number of arguments, and the kind of each literal argument, when the template compiles. A path argument is accepted anywhere and judged when the template runs. A filter also runs on an empty input. Every built-in filter turns an empty input (null, '') into an empty output, except default and count.

Filter Arguments Result
plain none Text without markup: tags removed (a tag boundary reads as a space), entities decoded, whitespace collapsed, trimmed.
limit:n integer Text cut to at most n characters (code points), at a word boundary when the cut falls inside a word. No ellipsis. A limit below 1 gives an empty value.
default:v any literal or path v when the value is empty, else the value.
upper / lower none The text in upper or lower case (multibyte-safe).
capitalize none The first character in upper case, the rest as written.
trim none The text without leading and trailing whitespace, no-break spaces included.
number:d integer, optional A numeric value as text with d decimals (default 0), . as separator, no grouping: "240.00".
round:p integer, optional A numeric value rounded half away from zero to p decimals (default 0). An integer stays an integer; a float is rounded to the precision, and becomes a whole number when p is 0 or less.
date:format string, optional A date in a PHP date() format, default ISO 8601 (2026-11-30T00:00:00+00:00), in the host's time zone. It reads date text (in the host's time zone unless the text names an offset) or Unix seconds. Anything else gives an empty value.
join:sep string, optional The items of a list as text joined by sep (default , , used only when sep is not given; join:'' joins with nothing). Items that are not text are left out.
first / last none The first or last item of a list (or value of an object). Any other value is its own first and last item.
count none How many items a list holds. An empty value counts 0. Any other value counts 1.
slug none A URL slug: transliterated to Latin ASCII (ext-intl), lower case, runs of letters and digits joined by -.
json none The JSON text of the value, slashes and Unicode unescaped.
abs none The absolute value of a numeric value.
replace:a,b string, string Every occurrence of a replaced by b.
prefix:s / suffix:s string s written before or after the text. An empty value stays empty.
url none A relative URL made absolute against the host's BaseUrlInterface. A URL with a scheme, or one that starts with //, stays as it is.

Values that are not text (lists, objects, value objects) make the text filters empty. Booleans read as true and false. Numbers read as their digits.

Compile errors

Every error has a path, a code, parameters and, inside a string, an offset in code points. The compiler reports all errors of a template at once.

Code Meaning
source-too-large, nesting-too-deep, expression-too-deep A limit is exceeded.
invalid-json, unsupported-value The source is not JSON, or holds a value JSON cannot hold.
unclosed-interpolation, empty-expression A {{ never closes, or nothing stands inside {{ }}.
unexpected-character, unterminated-string, number-too-large, unexpected-token, unexpected-end The expression does not read.
expected-path-segment, expected-filter-name, invalid-filter-argument, chained-comparison The expression has the wrong shape.
unknown-filter, filter-arity, filter-argument-type A filter is not registered, gets the wrong number of arguments, or gets a literal of the wrong kind.
directive-sibling, directive-requires, directive-value-type, reserved-name A directive sits next to a key it refuses, lacks one it needs, has a value of the wrong type, or has a reserved name.

The evaluator also reports notes to a recording trace: unknown-variable, not-a-list, include-missing, include-loop and include-too-deep.

Tracing

Pass a TraceInterface as the third argument of evaluate() to learn why a part of the output is missing. The default trace records nothing and costs nothing. RecordingTraceFactoryInterface::create() returns a recording trace.

$trace = $this->traces->create();
$this->engine->evaluate($source, $scope, $trace);

foreach ($trace->getEntries() as $entry) {
    // $entry->getPath(), $entry->getOutcome() (TraceOutcome::Value, Empty or Skipped),
    // $entry->getSources() (the variable paths an empty or skipped node read)
}
foreach ($trace->getNotes() as $note) {
    // $note->getPath(), $note->getCode(), $note->getParams()
}

For {"color":"{{ product.color }}","sale":{"@if":"product.on_sale","@value":"yes"}} and a product with an empty colour that is not on sale, the entries are $.color empty (reads product.color), $.sale skipped (reads product.on_sale) and $ empty. The evaluator builds a second set of closures for recording traces, the first time one is passed, so the closures of a plain evaluation keep no bookkeeping.

Public API

Everything under Api/ is the published surface. Classes under Engine/ and Model/ are internal.

Interface Role
TemplateEngineInterface Compile through the storage, evaluate, render.
CompilerInterface, EvaluatorInterface The two halves of the engine, without the storage.
ScopeFactoryInterface, ScopeInterface The variables of one evaluation.
JsonEncoderInterface JSON text, and JSON for a <script> element.
TemplateLiteralsInterface Outside text, written so the language reads it back unchanged.
Data\CompiledTemplateInterface, Data\CompileErrorInterface, Exception\CompileException The result of a compile and its errors.
Data\AstNodeKind, Data\ArgumentKind The node kinds of a compiled tree, and the literal kinds a filter accepts.
Data\ValueInterface A lazy value that a path can walk into key by key.
TraceInterface, RecordingTraceInterface, RecordingTraceFactoryInterface, Data\TraceOutcome, Data\TraceEntryInterface, Data\TraceNoteInterface What an evaluation did, node by node.
ItemAliasResolverInterface, IncludeResolverInterface, BaseUrlInterface, TimezoneProviderInterface, CompiledTemplateStorageInterface Ports the host implements.
FilterInterface, FilterPoolInterface A filter, and the pool of filters.
DirectiveCompilerInterface, DirectiveContextInterface, DirectiveCompilerPoolInterface The compile half of a directive.
DirectiveBuilderInterface, DirectiveBuilderPoolInterface The evaluation half of a directive.
NodeBuilderInterface, NodeBuilderPoolInterface, BuildContextInterface, EvaluationStateInterface Node builders and what they can do while they build and while a closure runs.
VariableProviderInterface, VariableProviderPoolInterface Variables supplied on first read.
CompileErrorFactoryInterface, CompiledTemplateFactoryInterface, TraceEntryFactoryInterface, TraceNoteFactoryInterface Factories for the data objects.

Extending

Every pool is filled in the global etc/di.xml. An area di.xml that names the same argument replaces the list.

A filter

Implement Api\FilterInterface: the arity, the kinds of the literal arguments, and apply(). A filter must be pure and must return null for an empty input.

namespace Vendor\Module\Template;

use Hryvinskyi\JsonTemplate\Api\FilterInterface;

class InitialFilter implements FilterInterface
{
    public function getMinArity(): int
    {
        return 0;
    }

    public function getMaxArity(): int
    {
        return 0;
    }

    public function getArgumentKinds(): array
    {
        return [];
    }

    public function apply(mixed $value, array $arguments): mixed
    {
        return is_string($value) && $value !== ''
            ? mb_strtoupper(mb_substr($value, 0, 1, 'UTF-8'), 'UTF-8')
            : null;
    }
}
<type name="Hryvinskyi\JsonTemplate\Engine\Filter\FilterPool">
    <arguments>
        <argument name="filters" xsi:type="array">
            <item name="initial" xsi:type="object">Vendor\Module\Template\InitialFilter</item>
        </argument>
    </arguments>
</type>

{{ name | initial }} now works. The key is the filter's name. The fingerprint of the registered filters is part of the cache key, so a new filter never reads an entry that was compiled without it.

A directive

A directive has two halves.

  • Its compiler, Api\DirectiveCompilerInterface, goes in the directives argument of Hryvinskyi\JsonTemplate\Engine\Directive\DirectiveCompilerPool, keyed by its name without @. It declares the siblings it allows (null means any) and the siblings it requires. It keeps an argument, replaces the object, or embeds an include.
  • When it keeps an argument, its builder, Api\DirectiveBuilderInterface, goes in the builders argument of Hryvinskyi\JsonTemplate\Engine\Evaluation\Directive\DirectiveBuilderPool, under the same name. The item is an array with a sortOrder and a builder. A lower sort order wraps a higher one. When the template is built, the builder receives the closure of what it wraps (the directives after it, then the body of the object). It returns the closure of the object. That closure calls the inner one zero, one or many times. It calls it through BuildContextInterface::child() when it makes items. The package's own sort orders are @as 10 and @limit 20 (they only qualify @each), @each 30 and @if 40. A compiled argument with no registered builder fails the evaluation loudly.
<type name="Hryvinskyi\JsonTemplate\Engine\Directive\DirectiveCompilerPool">
    <arguments>
        <argument name="directives" xsi:type="array">
            <item name="repeat" xsi:type="object">Vendor\Module\Template\RepeatCompiler</item>
        </argument>
    </arguments>
</type>
<type name="Hryvinskyi\JsonTemplate\Engine\Evaluation\Directive\DirectiveBuilderPool">
    <arguments>
        <argument name="builders" xsi:type="array">
            <item name="repeat" xsi:type="array">
                <item name="sortOrder" xsi:type="number">50</item>
                <item name="builder" xsi:type="object">Vendor\Module\Template\RepeatBuilder</item>
            </item>
        </argument>
    </arguments>
</type>

A node builder

Api\NodeBuilderInterface goes in the builders argument of Hryvinskyi\JsonTemplate\Engine\Evaluation\NodeBuilderPool (template nodes) or of its virtual type Hryvinskyi\JsonTemplate\Engine\Evaluation\ExpressionBuilderPool (expression nodes). The key is the node kind, one of the values of Api\Data\AstNodeKind. A builder returns the closure that evaluates its node. It does at build time every lookup that does not depend on the scope. It builds the nodes inside its own node through the BuildContextInterface it receives. isTracing() says whether the closures serve a recording trace: trace bookkeeping (read(), skip() and note() on the evaluation state) belongs in that variant only. A template node's closure yields null, not an empty value.

A variable provider

Api\VariableProviderInterface::provide($root, $scope) returns an array, a scalar, null or a ValueInterface. It never returns a model. It runs the first time a template reads its root.

<type name="Hryvinskyi\JsonTemplate\Engine\Scope\VariableProviderPool">
    <arguments>
        <argument name="providers" xsi:type="array">
            <item name="store" xsi:type="object">Vendor\Module\Template\StoreProvider</item>
        </argument>
    </arguments>
</type>

A variable you give to ScopeFactoryInterface::create() wins over a provider, and the provider is then never asked. The pool above is the global one. A module that wants roots only its own templates read gives its engine a scope of its own (see A scoped engine below).

What the host supplies

Each of these has a default. Replace one with a di.xml preference when every consumer of the package should share it.

Port Default
ItemAliasResolverInterface (item names) None: an item is read as item.
IncludeResolverInterface (included templates) None: every include is empty.
BaseUrlInterface (the site address for url) A relative URL stays relative.
TimezoneProviderInterface (the time zone for date) UTC.

A scoped engine instead of a global preference

A preference changes the engine for every module that uses the package. If one module needs its own item names or its own includes, give it its own engine. Declare virtual types in that module's di.xml, and inject the virtual engine into the classes that need it:

<virtualType name="Vendor\Module\Template\Evaluator"
             type="Hryvinskyi\JsonTemplate\Engine\Evaluator">
    <arguments>
        <argument name="itemAliases" xsi:type="object">Vendor\Module\Template\ItemAliases</argument>
        <argument name="includes" xsi:type="object">Vendor\Module\Template\Includes</argument>
    </arguments>
</virtualType>
<virtualType name="Vendor\Module\Template\Engine"
             type="Hryvinskyi\JsonTemplate\Engine\TemplateEngine">
    <arguments>
        <argument name="evaluator" xsi:type="object">Vendor\Module\Template\Evaluator</argument>
    </arguments>
</virtualType>
<type name="Vendor\Module\Service\SnippetWriter">
    <arguments>
        <argument name="engine" xsi:type="object">Vendor\Module\Template\Engine</argument>
    </arguments>
</type>

SnippetWriter types its constructor argument as TemplateEngineInterface. The two resolvers implement ItemAliasResolverInterface and IncludeResolverInterface. An include resolver turns a code into a compiled template with CompilerInterface::compile():

class Includes implements IncludeResolverInterface
{
    public function __construct(private readonly CompilerInterface $compiler)
    {
    }

    public function resolve(string $code): ?CompiledTemplateInterface
    {
        return $code === 'return-policy'
            ? $this->compiler->compile('{"@type":"MerchantReturnPolicy","merchantReturnDays":30}')
            : null;
    }
}

The scoped engine reads {"policy":{"@include":"return-policy"}} as {"policy":{"@type":"MerchantReturnPolicy","merchantReturnDays":30}}. The global engine reads the same template as empty, because the global default has no includes.

What the scoped engine shares with the global one, and how to scope more:

  • With only a scoped evaluator, the compiler and the compiled-template storage stay shared. The key of a stored entry depends on the source and on the filters and directives, not on the resolvers, so both engines read the same entries.
  • Each evaluator builds and keeps its own closures.
  • Own filters. Declare a virtual Engine\Filter\FilterPool with the module's filters, and pass it as filters to a virtual Engine\Compiler, a virtual Engine\Template\CompiledTemplateKey, and the virtual evaluator. Give the key to a virtual Model\Cache\CacheTemplateStorage and a virtual Engine\Template\MemoizingTemplateStorage (arguments inner and keys), and pass storage, compiler and evaluator to the virtual TemplateEngine. The key then carries the module's filter set, so its cache entries never mix with the global engine's.
  • Own roots. Declare a virtual Engine\Scope\VariableProviderPool with the module's providers, a virtual Engine\Scope\Scope with it as providers, a virtual Api\ScopeInterfaceFactory whose instanceName is that scope, and a virtual Model\Factory\ScopeFactoryAdapter with the generated factory as generated. Inject that adapter as the ScopeFactoryInterface of the classes that build the module's scopes. A variable passed to create() still wins over a provider.
  • An include that is itself a template. When the include resolver evaluates through the same scoped engine, inject the engine into it through a virtual Api\TemplateEngineInterface\Proxy, so the engine and its resolver do not build each other at construction.

Caching

CompiledTemplateStorageInterface keeps compiled templates by source, in two layers:

  • an in-process memory, so a process reads a source from the cache at most once;
  • the json_template cache type (tag JSON_TEMPLATE), which every process shares. The entry is the compiled tree written as JSON through Magento's JSON serializer, never PHP serialization. Maps and floats are wrapped, so a decoded entry is exactly the tree that was compiled (4.0 stays a float, an object stays an object).

The key is JSON_TEMPLATE_ plus xxh128(source), the version of the compiled form, and a fingerprint of every registered filter (name, arity, argument kinds) and directive (name). If a template changes, or a module adds, removes or redeclares a filter or a directive, every source gets a new key. A compiled form made without the change is never read. Entries do not expire. Flush of the cache type in Cache Management removes them. A disabled type stores nothing: each process then compiles a source once into its memory. An entry that cannot be read back counts as a miss.

Performance

Compilation happens once per source per deployment. The evaluator turns a compiled tree into closures once per process. It makes one closure per node and does at build time whatever does not depend on the scope. It keeps the closures by the hash of the template source, so every later evaluation only calls closures. There is no lookup by node kind and no reading of node arrays. Literal properties of an object are laid out once and copied. A string that is one variable path reads it in a single closure. Literal filter arguments are listed once. A recording trace gets closures of its own, so the closures of the storefront keep no JSON path, record no reads and never ask the scope whether an absent root exists.

An evaluation does no regular expression, no json_decode, no string splitting, no compiler call and no storage read.

php Test/Benchmark/product.php [evaluations] times the Product template in Test/_templates/product.json: about 70 nodes, a two-image gallery, five reviews limited to three, and an include. It prints the mean time of one evaluation of the compiled template, and of one evaluation through the engine facade, which also finds the compiled template in its memory by the hash of the source. The script builds the engine as di.xml wires it, with the built-in filters and without Magento.

Measured with 50,000 evaluations after a warm-up, on an Apple M5 Pro laptop, with no debugger:

Where PHP opcache Microseconds per evaluation (compiled template / through the engine)
DDEV container (Linux, x86_64), the Magento development setup 8.4.24 on, no JIT 10.5 to 11.2 / 10.9 to 11.4 (five runs)
macOS, command line 8.5.10 off 8.4 / 8.8
macOS, command line 8.5.10 on, no JIT 8.1 / 8.5
macOS, command line 8.5.10 on, JIT tracing 5.4 / 5.5

The target is 15 µs per evaluation. The numbers vary by machine and by load: run the script on your own hardware before you rely on them.

Security model

Templates are data, never code.

  • The language has no function call into PHP, no getter reflection and no file access. A path walks arrays and ValueInterface values only.
  • A filter exists only if a module registers it in the filter pool. Every built-in filter is pure.
  • The engine never reads a variable's value as a template, so data cannot add expressions, directives or includes to a template. An @include code is a fixed string in the template.
  • Variable providers expose arrays, scalars and ValueInterface values, never framework models.
  • A template is bounded at compile time (256 KB of source, 64 levels of nesting, 32 levels of expression) and at evaluation time (8 levels of include, no include loop).
  • Cached compiled forms are JSON, so a cache entry can only become data. Nothing is unserialized.
  • The evaluation path uses no regular expression and no json_decode. The package's own PHPStan rules enforce this (Test/StaticAnalysis/). In the namespaces that run during an evaluation (Engine\Evaluation, Scope, Value, Inclusion, Trace and Filter, and the Evaluator class) the rules refuse preg_*, mb_ereg*, json_decode, unserialize, explode, str_split, mb_split, mb_str_split, strtok, call_user_func*, a function called through a variable (a closure is the only callable value allowed), Closure::fromCallable(), and any call of CompilerInterface::compile() or CompiledTemplateStorageInterface::load(). A function-call rule cannot see inside a Closure that you call, so the unit tests also count the work of 1,000 evaluations of the Product template: one compile, one storage read, one resolution of each root per evaluation, and one build of the template's closures.
  • Escaping. The engine returns data. It does not escape for any output format. When you write JSON into HTML, use JsonEncoderInterface::forHtmlScript(), which no text inside the value can escape. When you write it anywhere else, choose the json_encode() flags for that place. The plain filter removes markup from a value. It is not a sanitiser for HTML output.

Limits

A source of at most 256 KB. Objects and lists nested at most 64 levels. Expressions nested at most 32 levels. Includes nested at most 8 levels.

Testing

  • Test/Unit runs without Magento: vendor/bin/phpunit -c phpunit.xml.dist from the package directory. It reads the shared cases in Test/_vectors (compile, compile errors, expressions, evaluation, literals) and the Product template in Test/_templates. A case is a template, a scope and the expected output or error.
  • Test/Integration runs in Magento's integration framework: the real container with its generated factories, the directive builder order, the cache storage and the data patch. From dev/tests/integration, run ../../../vendor/bin/phpunit -c phpunit.xml ../../../app/code/Hryvinskyi/JsonTemplate/Test/Integration.
  • Test/StaticAnalysis holds the PHPStan rules of the evaluation path. phpstan.neon.dist loads them and sets level 10.
  • phpcs.xml.dist applies the Magento 2 coding standard.
  • setup:di:compile proves the di.xml wiring.

License

MIT. See LICENSE.