Search by

PHP implementation of the Curly Message Format.

Package info

github.com/curly-message/parser-php

Issues

pkg:composer/curly-message/parser

Statistics

Installs: 5

Dependents: 0

Suggesters: 0

Stars: 0

v1.0.2 2026-12-04 16:57 UTC

This package is auto-updated.

Last update: 2026-12-04 16:59:14 UTC


README

Packagist tests

The PHP implementation of the Curly Message Format.

{
  "greeting": "Hello, {{name; default:Guest;}}!",
  "inbox": "You have {{count:number;}} {{count:plural; one:message; other:messages;}}."
}
greeting  ['name' => 'Alice']  ->  "Hello, Alice!"
greeting  []                   ->  "Hello, Guest!"
inbox     ['count' => 1]       ->  "You have 1 message."
inbox     ['count' => 1234]    ->  "You have 1,234 messages."

inbox resolves as shown at the locale en where ext-intl is loaded (see Intl). A placeholder may carry a modifier (:number, :date, :ago, :currency, one of the comparisons eq, ne, lt, lte, gt, gte, or one of the plural selections plural and ordinal), a set of options, and a default. A modifier that cannot produce a result, a value no conversion turns into text and a modifier nobody registered all resolve the placeholder to its fallback chain rather than raising, and each is reported to the caller. The specification says what every message resolves to; this page says what is particular to PHP.

Installation

composer require curly-message/parser

Composer reads the package from curly-message/parser-php, tagged vX.Y.Z there: a read-only repository that holds the history of this directory alone and is written only by the release workflow of curly-message/parsers, where the package is developed and each release is tagged php-vX.Y.Z.

It requires PHP 8.2 or newer and no extension beyond those PHP always carries (json, pcre, spl): no mbstring, no ctype, no iconv. ext-intl is suggested rather than required; with it the package satisfies the Intl level (see Intl), and without it the six locale-dependent modifiers are not there at all. PHP 8.2 is supported until its end of life on 2026-12-31; the first minor release after that date requires PHP 8.3.

Usage

use CurlyMessage\Parser;

$parser = new Parser();

$parser->resolve('Hello, {{name; default:Guest;}}!', payload: ['name' => 'Alice'], locale: 'en');
// 'Hello, Alice!'

A parser is built once with its options and resolves any number of messages. resolve takes the inputs resolution is defined over as named arguments, each of them optional:

Argument Meaning
message The message. A caller that supplies none, or Undefined::Value, resolves to ''.
payload The values the placeholders name, as an array or a stdClass. Its default entry is the message-wide fallback. Anything else is no payload.
props Formatting options for the modifiers, keyed by modifier name, as an array or a stdClass. A payload entry's own props layer over them.
locale The locale the locale-dependent modifiers format for: a string, cs-CZ or cs_CZ. Anything but a string is none.
id What each report carries to say which message it came from. No step of resolution reads it.

Each argument is mixed, so nothing a caller passes makes resolve throw a TypeError, under strict_types or not: a value of the wrong shape reads as none. resolve answers a string, always, with the one exception described under Re-entry.

The constructor takes four named options:

Option Meaning
customModifiers Modifiers the host defines, by name: see Modifiers a host defines.
modifierDefaults The props each modifier is configured with, by its name, beneath every other layer.
onReport Closure(Report): mixed, called with each report in the order the walk meets it.
recognizeWrappers Whether a payload entry holding only value, default and props configures its value (on by default).

Values

Everything the format carries is text, so a payload value reaches a modifier and the output as text, whatever type it holds:

PHP value Text
string itself, byte for byte
int its digits
float (string), at the precision ini (14 significant digits by default): 0.1 + 0.2 is 0.3, 1e15 is 1.0E+15
true, false 1, the empty string
null the empty string: a value that is present, not a missing one
array JSON
stdClass JSON
any other object its __toString; one with none (a DateTimeImmutable, an enum, an ArrayObject) has no text
Undefined::Value none: the entry is missing

A float carries no more digits than precision writes; a caller that needs more passes a numeric string. A value that has no text is read as missing: the placeholder takes its fallback chain, and the condition is reported as unserializable-value.

Plain data is an array, whatever its keys, and an object whose class is exactly stdClass. Both serialize to JSON as json_encode writes them, with slashes, characters outside ASCII and the two Unicode line terminators written as themselves: a list is a JSON array, any other array a JSON object, and an empty array []. So {} in PHP is (object) [].

['v' => [1, 2]]           ->  [1,2]
['v' => ['a' => 1]]       ->  {"a":1}
['v' => []]               ->  []
['v' => (object) []]      ->  {}
['v' => [0 => 'a', 2 => 'b']]  ->  {"0":"a","2":"b"}

Inside plain data an object serializes as json_encode would serialize it: a JsonSerializable as what its jsonSerialize() answers, a backed enum as its value, a Closure as {}, and any other object as its public properties, so a DateTimeImmutable nested in an array is {"date":...,"timezone_type":..., "timezone":...}. On PHP 8.4 and newer that includes what json_encode runs: each property hook's get, and a lazy object's initializer. That is host code, and it is contained: one that throws makes the value one with no text. An entry holding Undefined::Value is left out of an object and written null in a list, as JSON writes ECMAScript's undefined. A cycle through objects, a pure enum, a string that is not UTF-8, INF and NAN have no JSON, so the value has no text.

A value is converted once per resolution however many placeholders name it, so an object's __toString or jsonSerialize() runs once for the resolution, and the message counts too: resolve($object, payload: ['x' => $object]) asks $object once. A PHP array has no identity, so an array is converted once for each place it is read at: each key of the payload, and a wrapper's value or default. Read there again, an equal array answers the text it converted to, and one host code put there since converts, as far as the resolution compares what it reads again. So an object inside an array runs its jsonSerialize() once for each key that holds the array, where the JavaScript parser runs it once. What a host modifier answers is let go with its call (see Modifiers a host defines), so an array it answers converts at each placeholder that asks for it, the same list answered again included, where the JavaScript parser converts a list a modifier answers again once. Each such conversion is bounded as any is, by the values it visits and the text it writes, so what a modifier's answers cost grows with the placeholders of the message, by no more than one conversion each, and how much is the modifier's own choice: one that answers a long list at many placeholders converts it at each. A read of a value while its conversion is under way, from the value's own __toString or from a fiber while the one converting it is suspended, converts nothing: the value has no text there, and the read reports unserializable-value, where the JavaScript parser converts it again from inside the first. A conversion a fiber was let go in the middle of never finishes, and the value has no text for the rest of the resolution. What a resolution recorded of arrays is let go as its resolve returns, and nothing converts on its account after that: a conversion a fiber left suspended in a value's jsonSerialize() and resumes then asks nothing more of the value, and a text host code reads then answers what the resolution rendered of it (see Modifiers a host defines). A conversion visits at most 100 000 values, and the JSON it writes stops at 536 870 888 bytes; past either the value has no text (see Limits). What an object answers for its text is the object's text however long, as a string's is.

Missing and null. PHP has one null, and the format needs two meanings: a value that is there and empty, and one nobody supplied. null is the first: ['v' => null] holds v, and {{v; default:D}} renders the empty string. CurlyMessage\Undefined::Value is the second, and wherever the format reads the host's undefined it is that: a payload entry holding it is missing, a wrapper's value holding it has no value, a default holding it is a link that is not there, and a layer property holding it is a property the layer does not name.

Containers are read from their own entries only: an array by array_key_exists (so a null entry is found) and a stdClass by its properties. __proto__, constructor and toString are keys like any other. No other object is a container, because reading one would run its ArrayAccess or __get, so a payload, a layer or a registry of any other class is none. PHP reads the key "1" as 1, so {{1}} finds ['1' => ...] and [1 => ...] alike.

Wrappers. An entry holding nothing but value, default and props configures its value: ['v' => ['value' => 3, 'props' => ['number' => [...]]]]. A caller that passes data it did not write turns that off with recognizeWrappers: false: an entry of that shape is then a value like any other, and nobody can reconfigure a modifier by writing data in that shape.

Props. A modifier is handed the props every layer holds under its name, composed: modifierDefaults, then the call's props, then the wrapper's own. They arrive as a CurlyMessage\Props, which is read as an array is ($props['style'], isset, foreach, count), and by has, get and toArray, the last an array of the caller's own. A resolution composes the first two layers once for each modifier name, and every placeholder naming that modifier is handed the same properties. A wrapper's own are laid over them where they are, neither copied, so what a placeholder costs is what its modifier reads, never what the layers hold, and nothing kept grows with the keys of a message times what the layers hold. The properties are therefore read-only: writing into them throws a LogicException, which fails the modifier that tried as any raise of its own does. A shared layer host code changes while a resolution is in progress is read as it was when a placeholder first composed it; the next resolution reads it afresh. A host builds its own Props from its layers, the uppermost first, to hand a modifier it tests: new Props([['style' => 'percent'], $defaults]), where Undefined::Value under a name leaves the property to the layers beneath.

Comparisons

eq and ne compare the value and each option key in lower case, by Unicode's own mapping (Default Case Conversion, with the final sigma): PHP's strtolower maps ASCII only, and mb_strtolower belongs to an optional extension and answers differently from one PHP version to the next, so the package carries the mapping itself, generated from the Unicode Character Database 17.0.0. No locale is applied and nothing is normalized.

lt, gt, lte and gte read the value and the keys as numbers by PHP's numeric strings, once the format's whitespace class (SPEC.md section 6) is removed from both ends: is_numeric skips ASCII whitespace alone, so the package removes the class, U+3000 and U+FEFF among it, first. So 12, 1e3 and .5 are numbers, and 12px, 0x1A, 1_000, the empty string and Infinity are not. A value that is no number is neither less nor greater than any key; lte and gte still select an option whose key equals it, as eq would.

A number is a double (SPEC.md section 4), whatever PHP reads the text as: integer text is read as the double nearest it, never as a PHP integer. So 9007199254740993 and 9007199254740992, which round to one double, are one number, to these comparisons and to the Intl modifiers alike, and -0 keeps its sign.

Intl

The locale-dependent modifiers, number, date, ago, currency, plural and ordinal, are performed by ext-intl, which binds ICU. Parser::levels() says which levels this host satisfies: core, intl and extensions where ext-intl is loaded and ICU's plural rules and relative-time data are readable, and core and extensions where they are not. Without them the six names are not registered at all: {{n:number}} is a modifier nobody registered, reported unknown-modifier, and a host may register its own modifier under any of the six names.

A request is stated as ECMAScript's Intl states it, in its vocabulary (maximumFractionDigits, dateStyle, numeric), and its options are read as ECMA-402 reads them, with its defaults and its range errors. ext-intl has no binding for plural rules or relative time, so those two are performed from ICU's own data, read through ResourceBundle, by ICU's own algorithm: plural operands come from the digits number would show, so in Czech 1 is one, and many under minimumFractionDigits: 1, which shows it as 1.0; the text 1.0 is one, since number shows it as 1. ECMAScript's default grouping, which leaves 1234 ungrouped in Polish where ICU's formatter groups it, is applied from the locale's minimum grouping digits.

Locales. A locale is checked before any formatter is built. It must be a Unicode locale identifier (UTS #35), written with - or with _, so cs-CZ, cs_CZ and de-u-nu-arab are locales; ICU's own de@collation=phonebook is not, and keywords are written as -u- extensions. A locale that fails the check is one the host rejects: the placeholder takes its fallback chain and reports failed-modifier. A well-formed locale ICU has no data for formats at PHP's default locale (Locale::getDefault()), as ECMAScript formats at its own. No locale, or the empty string, resolves a locale-dependent placeholder to the empty string and reports missing-locale.

Ratios. currency's ratio is a property, which the whitespace class of SPEC.md section 6 does not reach, so a string ratio is read as PHP reads a numeric string (is_numeric): 2\n is 2, while 2 padded with whitespace outside ASCII, U+3000 or U+00A0, is no number, and the placeholder takes its fallback chain and reports failed-modifier.

Dates. date reads a value as milliseconds since the epoch first wherever it reads as a number (SPEC.md section 11.2), so 2024, 2024 and +002024 are each the 2024th millisecond, never a year. Other text is read by PHP's own date parser, where it names a date: date_parse reads it without an error or a warning, with a year, a month and a day, and with nothing relative but a weekday that is the date's own. Text with no offset is read in PHP's default time zone, a date alone included: 2024-03 and 2024-03-05 are midnight there, as 2024-03-05T10:00 is ten o'clock, while 2024-03-05T10:00:00.123Z is at UTC. So the RFC 2822 form Tue, 05 Mar 2024 10:00:00 +0000 is a date, and now, tomorrow, +1 day, a lone a, Wed, 05 Mar 2024 (a Tuesday), 2024-02-30 and 2024-03-05T24:00 are not.

What ext-intl cannot express. Parser::unexpressible() lists, by facility, the properties no value of which can be performed here, and none of them is read:

Facility Properties
NumberFormat notation, compactDisplay, signDisplay, unit, unitDisplay, currencySign, localeMatcher
DateTimeFormat formatMatcher, localeMatcher
RelativeTimeFormat localeMatcher
PluralRules localeMatcher

Below ICU 69, roundingMode joins NumberFormat and PluralRules: the half-ceiling, half-floor and half-odd modes arrived there.

hourCycle and hour12 are performed with the date and time components, and not with dateStyle or timeStyle: a style's pattern writes the day period of the locale's own hour cycle, so a style is formatted as the locale writes it ({ timeStyle: 'short', hourCycle: 'h23' } at en is 1:05 PM). Both are still read, and a value ECMAScript refuses fails the request. A locale's hc keyword likewise applies to the components and not to a style. Beside dateStyle alone, which shows no hour, the two change nothing. Parser::unexpressible() lists each of the two under DateTimeFormat with each timeStyle value it is not performed beside, as ['property' => 'hourCycle', 'when' => ['timeStyle' => 'short']].

The hour is as wide as ICU's pattern for the request writes it, so hour's numeric and 2-digit give the same text: { hour: '2-digit', minute: '2-digit' } is 1:05 AM at en and 1:05 at ja, and { hour: 'numeric', minute: '2-digit' } is 01:05 at de, where V8 writes 01:05 AM, 01:05 and 1:05. ext-intl's pattern generator cannot be asked to match the hour's width. ECMA-402 takes each field's width from the format the locale's data offers, so this is the property performed, by the one format matcher there is here, and Parser::unexpressible() does not list it.

What is kept. Formatters are kept for reuse, at most 256, and what ICU's data says of a locale, at most 64 locales of each kind, the oldest making room. A formatter is kept by its locale and by the properties its facility reads, the ECMA-402 properties it performs; those it cannot express in any request, which Parser::unexpressible() lists by name, and any other name the props hold are ignored and keep nothing more. A request whose locale, or the value of a property its facility reads, is longer than 64 bytes as it is written is built every time and not kept. Where a plural's properties settle the digits it selects by for every number, its rules hold a formatter that shows those digits, shared by the rules of every locale that settle the same; 16 are kept by their digits, the oldest making room. Where the props a placeholder is handed are a parser's modifierDefaults alone, kept as Limits says, the formatter each modifier asked for in a locale is found again without reading them, in 64 locales for each modifier, the oldest making room. These live in static properties, so under PHP-FPM or mod_php they last one request, and each request pays for building the first formatter of each locale and kind it uses.

Modifiers a host defines

use CurlyMessage\ModifierInput;

function shout(ModifierInput $in): string
{
    return strtoupper($in->value) . '!';
}

$parser = new Parser(customModifiers: [
    'shout' => shout(...),
    'initial' => fn(ModifierInput $in): string => substr($in->value, 0, 1),
]);

$parser->resolve('{{name:shout}} {{name:initial}}', payload: ['name' => 'ada']);
// 'ADA! a'

A modifier is a Closure or an object with __invoke, called with a ModifierInput: the value's text in value; the options the placeholder declares in options, each an Option whose key is its key and whose value() renders its value on the first call; the props the layers hold under the modifier's name in props; the locale, or null; and default(), which walks the fallback chain on the first call. An option that is never asked for is never rendered. A text the parser reads itself, the fallback chain of a modifier that failed or answered nothing, is bounded by the nesting limit and never throws. A text host code asks for, value() or default(), from the call of the modifier it was handed to, a resolution that call began among it until a modifier is called there, renders where the message nests it, one level beneath its placeholder, which the nesting limit bounds, and takes none of the places Re-entry counts. One asked for from anywhere else (a modifier that kept it from another placeholder, a fiber, a report handler, a value's __toString) renders outside where the message nests the read, at the level the text was declared at, which the nesting limit does not count. So it takes a place among the resolutions in progress on its thread of execution while it renders, as a resolve begun there does: texts read each inside the one before nest 31 deep beneath the resolution they belong to, and the read that finds no place is refused: it renders nothing, answers the empty string and fails nothing, as section 13 asks, so whatever made the read goes on with the empty string, and what a modifier then answers is taken as any answer is. A refused read throws nothing, and the text stays to be read where there is a place. A read that returned holds none, so a message may read any number of kept texts one after another. A read begun in a fiber where nothing is in progress is never refused, as a resolve begun there is not, so reads that each begin in a fiber of their own are the host's to bound (see Memory). The JavaScript parser bounds such reads by its engine's stack instead, about 1 000 deep under Node 22's default, so a message that reads more than 31 texts, each inside the one before, fails at the 32nd here where it resolves there. Once the resolution returned, a read answers the text a read during the resolution rendered, and the empty string where none finished one: nothing is rendered, reported or run on the resolution's account then, as section 11.3 asks, and a rendering a fiber left suspended in the resolution and resumes then resolves nothing more and answers the empty string. Host code gets one rendering of a text at a time: a text it asks for, while its resolution is in progress, once a rendering of it began and before one finished, in any fiber, is refused at once, whatever places there are: it is never rendered a second time and never waited on, and the read answers the empty string and fails nothing, as above. So a modifier that reads its kept option again from a placeholder nested in that option, or one that asks for a text a fiber left suspended mid-render, or let go of mid-render, reads the empty string. A text renders once: where a fiber left a rendering of a fallback chain suspended, or let go of it mid-render, the parser's own read of that chain resolves to the empty string rather than render it again, which would double what each level of a message walks; the JavaScript parser cannot suspend a rendering, so it never meets this. Every read after the one rendering finished answers its text. A ModifierInput is built for one call, so a modifier may sort options, which reaches nothing else; props it reads and does not write (see Props under Values). A function name or an array callable is not a modifier and registers nothing; shout(...) makes a Closure of a named function. The registry is read once for each resolve, before the walk (section 14.3): a modifier host code registers, replaces or removes while a resolution is in progress reaches the next one, never a later placeholder of the one in progress. An entry held by reference ('up' => &$up) is read as its variable held it as the call began.

A modifier that throws takes the fallback chain and reports failed-modifier, and so does one whose answer, or anything it hangs on its ModifierInput, throws as the parser releases it (a __destruct). Whatever a value, a modifier or a handler throws is released inside the parser too, its own __destruct and those of the arguments its trace holds included, and so is what the parser read of the payload, the props and the modifiers, which it holds until the resolution ends: where host code drops its own reference to an entry while the parser reads it, or the caller hands over what nothing else holds, the parser lets go of the last one inside the containment. So nothing they run as they go leaves resolve. A __destruct PHP's cycle collector runs is the host's garbage rather than code the parser called, and what it throws leaves wherever the collector ran, as in any code: out of resolve, or, where the collector ran inside what the parser contains of a placeholder, as that placeholder's failure. One that answers null or Undefined::Value answers nothing, which is PHP's way for a function to answer nothing (a return;, a function that ends without one), so the placeholder takes its fallback chain and nothing is reported. Any other answer converts to text as a payload value does. A host modifier under the name of one of the format's own replaces it.

Reports

use CurlyMessage\Report;

$parser = new Parser(onReport: function (Report $report): void {
    error_log("{$report->code->value}: {$report->text}");
});

$parser->resolve('{{v:nope; default:D}}', payload: ['v' => 1], id: 'greeting');
// 'D', and onReport is called with unknown-modifier, origin message, id 'greeting'

The parser writes nowhere itself: onReport is where diagnostics go. A Report carries code (a ReportCode), origin, what the condition is a defect of (an Origin: message, payload or limit), an English message, the id the resolution was given, the limit for the three codes that reach one (for output-limit below the message, MAX_TEXT_LENGTH), and text, the placeholder that reported, as the message spells it. text is never payload text. It is cut to 120 bytes, stepping back over at most three bytes so the cut never splits a character, marked ... where cut, and escaped as a JSON string's contents, with every line terminator the format knows escaped, so no message can forge a line where a report is written. A handler that throws is contained, and nothing it answers changes the resolution.

Limits

Limit Constant Value
what the placeholders of one resolution place in its output Parser::MAX_OUTPUT_LENGTH 100 000 bytes
value text one resolution reads from its payload Parser::MAX_READ_LENGTH 100 000 bytes
values one conversion visits Parser::MAX_CONVERSION_NODES 100 000
text the parser writes: one value's JSON, and what a level below the message holds as it places a result Parser::MAX_TEXT_LENGTH 536 870 888 bytes
levels of placeholder resolved, the outermost first Parser::MAX_NESTING 8
resolutions in progress on one thread of execution; a fiber is a thread of its own, and an option or a fallback chain host code reads outside the call it was handed to takes a place while it renders Parser::MAX_REENTRY 32

A PHP string is bytes, so the length limits count bytes, what strlen counts: 100 000 bytes hold 100 000 ASCII characters and 50 000 two-byte ones. MAX_TEXT_LENGTH is the longest string a 64-bit V8 holds, which V8 counts in UTF-16 code units and this parser in bytes. It is this parser's text length in the sense of section 13, which lets an implementation document one no shorter than 100 000 000 units and leaves what a resolution answers past it to the implementation: here, what this section says, and past it a text this section does not refuse, the output at the message or the lower case of a key or a value, is answered as at any length. A placeholder whose result would carry the output past its limit resolves to the empty string and reports output-limit, and so does one below the message whose result would carry its level's text past MAX_TEXT_LENGTH; one that begins after the payload's reading passed its limit resolves to the empty string and reports read-limit; one whose value would serialize to more JSON than MAX_TEXT_LENGTH, or visit more values than a conversion visits, as a list that holds itself through a reference does, takes its fallback chain and reports unserializable-value; one nested deeper than 8 levels takes its fallback chain and reports nesting-limit. The fallback chain of a placeholder past that depth is walked on a stack of the parser's own, so a message nested any deeper resolves on the same number of PHP frames. A value serializes on a stack of the parser's own as well, so no depth of its own refuses it: each array or object open on its path is a value visited, and MAX_CONVERSION_NODES alone bounds how deep it nests. A value nested 100 000 arrays deep serializes, and one nested 100 001 deep takes its fallback chain and reports unserializable-value. A comparison lowers the value only where it is short enough to equal a key, so eq and ne over a long value make no text at all.

No limit counts the work done on what a modifier is handed before it answers (SPEC.md section 13), so here is what that work grows with. The times are rough: taken on PHP 8.3 on one 2.1 GHz cloud server core, and a slower machine takes a few times as long.

  • Padding around an option's key or value, or an inline default (section 8), is removed one blank at a time from each end. The text between is not read. The work grows with the padding the message writes there, and is done each time the placeholder is resolved: about 130 ms for 1 MiB of padding, ASCII or U+00A0 alike.
  • An option key read as a number by lt, gt, lte and gte, a value read as a number by those and by the Intl modifiers, and a property read as a number, such as a string maximumFractionDigits, go through is_numeric once, which reads the whole text. Where it refuses the text, the whitespace class is removed from both ends, reading the padding and at most one slice past it. The work grows with the text and, more steeply, with its padding, and padding outside ASCII costs most. A key or a value is read at each placeholder that reads it as a number; a value is no longer than the read limit allows, and one padded with 48 000 U+00A0 takes about 0.6 ms. A property's text, or a list of that one text, is read once in a resolution, however many placeholders and wrappers ask for it: for 1 MiB of U+00A0 padding about 5.5 ms, and about 1.5 ms for 1 MiB of ASCII spaces, with 100 placeholders over it adding about 4 ms. The resolution remembers the number by the text the layers hold, so it keeps no text of its own, and lets it go when it returns. Any other list joins to a text of its own, which is not kept, so it is joined and read again for each request that reads it, which grows with its entries and its text: about 40 ms for 100 000 entries.
  • Props composed from their layers: modifierDefaults and the call's props are composed once in a resolution for each modifier name, which grows with the properties they hold under that name. For 100 000 properties that is about 7 ms, the same for one placeholder as for 100. Where the call's props hold nothing under that name, and modifierDefaults is an array that holds no stdClass there and no reference, which nothing can change once the parser is built, they are composed once for the parser instead, and kept beside it for as long as it lives: one composition for each name they configure, and one more for plural with the digits it takes from number. A wrapper's own props are laid over them uncopied, and an Intl modifier reads only the properties its formatter reads, by name. So what a placeholder costs does not grow with what a wrapper holds: 100 placeholders over a wrapper of 100 000 properties take what they take over one of 10. A host modifier pays for what it reads: toArray and foreach walk every layer.

What is kept

What a message's text settles alone is kept from one resolution to the next: what each placeholder declares, and the walk of the message and of each option: its text between placeholders, unescaped, and where each placeholder opens and closes. Of a message whose walk is not kept whole, where each of its opening pairs closes is kept as well. The records are the process's, shared by every parser in it, in a static property as the formatters are, so a parser holds nothing more and serializes as it did.

  • Nothing is kept of the first 16 messages with a placeholder that a process resolves. After them one message in 16 of those not kept, at gaps drawn at random, is read whole and kept, so a message is kept in proportion to how often it is resolved.
  • A process that resolves each message once is spared the records: once 64 messages in a row are looked up and none is found kept, one message in 64 is looked up and the others are resolved as if nothing were kept, until one is found. Such a process pays a counter decrement for each message passed over, and a hash and a lookup for one in 64: a bare placeholder in a text new to the process took about what 1.0.1 took, and a line of a catalogue what it took. A process that turns to resolving messages again takes a few thousand resolutions to keep them, more for a few hundred messages.
  • The records are counted as holding 1 MiB at most, each by more than PHP holds for it, and the oldest make room. A message longer than 8 KiB is not kept. Of one whose record would be counted past 16 KiB, which about 20 bare placeholders come to, or one placeholder of 16 options, the text alone is kept, so that it is not read for a record again. A megabyte holds the records of some 350 to 470 lines of a catalogue that declare no option, such as Hello, {{name}}!, about 150 of lines with a selection or a plural of two or three options, and 100 to 130 of lines that nest placeholders in their options, such as a plural of three options each writing {{count}}. A resolution in progress holds its record until it returns, kept or not.
  • A message is found by a hash of its text under a secret drawn once for the process, so no author of messages chooses texts that are found slowly. Where the system gives no random bytes, nothing is kept.

A record changes nothing a message resolves to or reports. It serves a message a process resolves again: a long-running worker, or the rows of one request. Under PHP-FPM or mod_php the records last one request, as every static property does. Cst::parse reads each message afresh.

Memory

The limits bound what a resolution does by its message, as section 13 asks, and the text it writes by MAX_TEXT_LENGTH; they do not ask how much memory is free. PHP ends a process that passes memory_limit with a fatal error no catch sees, and no code the parser runs can contain it: that is the host ending the process, as it would for any code, and a host sizes memory_limit for what it resolves. What a resolution holds is bounded by its message, by MAX_NESTING, by MAX_TEXT_LENGTH and by the re-entry bound, and none of it grows with anything outside the call; beside it the process holds the records of what is kept, a megabyte at most, which a host that sizes memory_limit closely counts in; and beside each parser that lives, its modifierDefaults composed as Limits says, and what each Intl modifier asked of them in each locale, as Intl says. Beside what they hold, that is about 3 KB for each modifier they configure that a placeholder has formatted through them in one locale, and about 200 bytes for each further locale, up to 64, more where they set many properties: about 15 KB for one modifier in 64 locales, and about 90 KB for defaults that configure all six Intl modifiers, each formatted in 64. It grows with the parsers a host keeps alive, not with what they resolve, and goes with each parser. Within those bounds, these end a process at PHP's default memory_limit of 128M, measured on PHP 8.3 by tools/memory.php in the shape each row names, which it runs at another limit too. Another shape holds what its row says it holds, and ends the process where that comes to 128M:

What Ends the process at 128M from about
a message declaring many options, each held as the placeholder resolves: about 0.7 KB for each 182 000 options in one placeholder, a message of about 910 KB; less where resolutions re-enter, each holding its own
a value whose JSON is long, which the parser writes before it measures what it places: a string shared many times, or a key of characters that escape 124 MiB of JSON, as one string of 1 MiB shared 124 times, or a key of 13 MiB of control characters, each written as six
a long text a level below the message places with text around it, held about three times over as the level writes it (what it places, the level's own text, and the text the level returns) at any depth an answer, or a value, of about 42 MiB; an answer placed with nothing around it is held once, and ends it from about 124 MiB
a recursion that resolves each level in a fiber of its own, which no bound the parser keeps reaches and the host bounds (see Re-entry), each level holding its fiber, its own message and the options it hands a host modifier, and what its placeholders declare only until the message is kept a message of one option that includes itself so: about 4 900 levels through a host modifier it hands its options to, and about 6 100 through a value that resolves it again
a recursion that resolves its levels by turns in a fiber of its own and beneath the one before on its stack, which no bound the parser keeps reaches either, each pair of levels holding one fiber and what two levels hold of the message a message of one option that includes itself so through a value that resolves it again: about 10 200 levels
host code that reads options it kept one inside another, each in a fiber of its own, while the resolution is in progress, which no bound the parser keeps reaches and the host bounds, as it does the fibers: about 24 KB for each about 5 300 options, a message of about 74 KB
fibers the host keeps, which the parser does not count about 7 600 fibers, at about 17 KB each, the host's alone
a list an Intl modifier's props hold, which it reads as text, as ECMAScript's String() joins one, up to MAX_TEXT_LENGTH 124 MiB of text, as one string of 1 MiB shared 124 times
a refusal's trace, which refers to the arguments of every frame beneath it unless zend.exception_ignore_args is on, as production configurations set it what the host's frames pass, kept until the refusal is let go

A thread-safe (ZTS) build keeps each thread's counts apart, as a fiber's are; it is not tested.

Re-entry

A host modifier, a report handler or a __toString may call resolve again, or ask for an option or a fallback chain (see Modifiers). PHP ends a recursion that never stops with a fatal error at its memory limit, which no catch sees, so the parser bounds it itself, as section 13 lets an implementation stand in for the host's own limit: each resolve takes a place on its thread of execution, and one begun while 32 are taken there throws CurlyMessage\ReentryLimit before it reads anything. An option or a fallback chain read by the call of the modifier it was handed to is part of the walk of its resolution and takes no place, so a resolution's own walk never meets the bound however deep its message nests. One host code reads from anywhere else renders outside that walk, at a level the nesting limit does not count, and takes a place while it renders as a resolve begun there would: a read begun while 32 are taken is refused, answering the empty string and failing nothing (see Modifiers). So resolutions that resolve others beneath them, as an include does, nest 32 deep on one thread of execution before the 33rd is refused, where the JavaScript parser, which bounds them by its engine's stack, resolves them deeper.

A fiber has a stack of its own, so it is a thread of execution of its own and counts its own places: what one fiber holds, suspended or not, takes nothing from another's 32, and a fiber started or resumed inside a resolution begins from its own count. A resolve begun on a thread of execution where nothing is in progress, in main code or at the top of a fiber, is never refused, as section 13 asks, however many resolutions are in progress elsewhere, and one begun beneath another is refused by the count of its own thread alone, however many fibers are suspended in resolutions. So a recursion that begins its levels in fibers of their own, as an async host awaiting each call does, reaches no bound the parser keeps, whether each level begins in a new fiber or only every other one does while the rest resolve beneath it on its stack: it is the host's to bound, as the fibers it starts are, and PHP's memory limit ends one the host does not, with a fatal error rather than ReentryLimit (see Memory). Section 13 asks the bound per thread of execution and leaves one across them to the implementation; the other implementations of the format keep none either. Once a resolution returned nothing resolves on its account (see Modifiers), so texts host code kept and reads later begin nothing and take no place.

ReentryLimit is all resolve ever throws, but for what a __destruct PHP's cycle collector runs inside it throws (see Modifiers). A refused read of an option or a fallback chain throws nothing. ReentryLimit lands in the host code that called resolve, which the placeholder that called that code contains as it contains anything that code throws: a modifier takes its fallback chain and reports failed-modifier; a value's __toString or jsonSerialize gives no text, so its placeholder takes its fallback chain and reports unserializable-value; and a report handler's raise changes nothing. The resolution around it answers as usual.

Describing a message

Cst::parse describes a message as it is written, by the same scan that resolution reads it with, as the tree CST.md specifies.

use CurlyMessage\Cst;

$tree = Cst::parse('Hi {{name}}');
// $tree->type is NodeType::Message, $tree->nodes its text and placeholder

$tree->toArray();
// ['type' => 'message', 'start' => 0, 'end' => 11, 'nodes' => [
//     ['type' => 'text', 'start' => 0, 'end' => 3],
//     ['type' => 'placeholder', 'start' => 3, 'end' => 11, 'nodes' => [...]],
// ]]

Every node is a CurlyMessage\Cst\Node carrying type, start and end; nodes on a message, a placeholder, a name and an option value; name on a key, a modifier name and an option key; and cancels on an escape. Spans are byte offsets into the PHP string read as UTF-8 (Cst::UNIT is 'utf-8'), so substr($message, $node->start, $node->end - $node->start) is what a node spans. toArray() answers CST.md's interchange encoding as PHP arrays, built without recursing. json_encode of those arrays recurses, and refuses a tree past its depth, 512 by default; give it a depth of 4 * nesting + 8 or more, where nesting is how deep the message nests its placeholders. PHP frees nested arrays by recursing into them, so the arrays of a tree nested tens of thousands of levels deep can take the process down when they are dropped; the Nodes themselves are released one level at a time, and a tree that deep is walked through them.

Conformance

This package implements curly-message-3, version 3 of the format, and satisfies Core and Extensions on every host, and Intl where ext-intl is loaded: Parser::levels() answers which.

Its suite runs the specification's conformance set, @curly-message/conformance 4.3.0, fetched and checked against its published SHA-256 digest, through a runner of its own, with ext-intl and without it, and over the set's tree cases. The runner leaves out the cases whose inputs hold values that refuse to be read, since what PHP hands the parser to read is plain data.

Development

Run from this directory:

composer install       # the package, its suite's dependencies and the tools in tools/qa/
composer test          # fetches the set, lints, analyses, runs the suite, then composer test:dist
composer test:dist     # the archive a release ships, installed by copy and tested there
composer lint          # the formatting contract and the source checks; composer lint:fix fixes the first
composer analyse       # PHPStan at its highest level
composer unicode       # regenerates the case table from the pinned Unicode data
composer bench         # the benchmark; composer bench -- --compare <dir> beside another checkout
php tools/memory.php   # what ends a process at 128M in each shape of Memory; php tools/memory.php <limit> at another

The benchmark runs on Node.js 22 or newer, as the family's harness does.

License

MIT