Search by

eugene-erg / icu-message-format-parser

EugeneErg

ICU MessageFormat parser: typed AST, flattening into variants and compact rebuilding

Package info

github.com/EugeneErg/icu-message-format-parser

pkg:composer/eugene-erg/icu-message-format-parser

Statistics

Installs: 788

Dependents: 10

Suggesters: 0

Stars: 1

Open Issues: 0

3.0.0 2026-12-03 15:40 UTC

README

A strongly-typed, zero-dependency PHP 8.2+ library for parsing, serialising, and transforming ICU MessageFormat strings — including flattening a message into plain variants (for translators and MT engines) and rebuilding the shortest equivalent message from edited or translated variants.

CI PHPStan PHP License: MIT

Table of Contents

Features

  • Full ICU MessageFormat parsing — select, plural, selectordinal, number, date, time, spellout, ordinal, duration
  • Complete ICU Number Skeleton support — all tokens from the ICU spec, including concise forms (E0, K, KK, +!, ,_, 000, …)
  • Lossless round-trip — parse → serialise returns the canonical ICU form
  • Structural flattening — convert any branching message into a flat list of linear variants
  • Compact rebuild from variants — edited or machine-translated variants are factored back into the shortest equivalent message: shared text is written once and selectors wrap only the words that differ
  • intl-safe output — rebuilt messages are accepted by MessageFormatter (# scoping, {n, number} where # is not available, quoted literal #)
  • Equivalence checker — verify with php-intl that two messages format identically for every branch
  • Domain exceptions — every error implements Exceptions\ExceptionInterface
  • Strongly typed — every ICU construct has its own readonly class or enum; no stringly-typed magic
  • Zero PHP extensions required — standard mbstring / pcre only (intl is optional, used by the equivalence checker)
  • PHP 8.2+ features — readonly classes, enums, named arguments, intersection types throughout

Installation

composer require eugene-erg/icu-message-format-parser

Quick Start

use EugeneErg\ICUMessageFormatParser\Parser;

$parser = new Parser();

// 1. Parse an ICU string into a typed object tree
$types = $parser->parse(
    '{gender, select, male {He} female {She} other {They}} liked {count, plural, one {1 post} other {# posts}}.'
);

// 2. Flatten all branching into a linear list of variants
$cases = $parser->typesToCases($types);
// → 3 gender × 2 plural = 6 flat variants

// 3. Inspect every variant
foreach ($cases->types as $variant) {
    echo (string) $variant, PHP_EOL;
}
// He liked 1 post.
// He liked {count, number} posts.
// She liked 1 post.
// She liked {count, number} posts.
// They liked 1 post.
// They liked {count, number} posts.

// 4. Rebuild from flat cases back into a structured Types tree
$rebuilt = $parser->casesToTypes($cases);
echo (string) $rebuilt; // the original message again (shared text written once)

Core Concepts

Types — the message container

Types is an ordered, immutable sequence of ICUTypeInterface elements. It is the central value object of the library.

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Types;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Pattern;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Variable;

$types = new Types([
    new Pattern('Hello '),
    new Variable('name'),
    new Pattern('!'),
]);

echo (string) $types; // Hello {name}!

Key Types methods:

Method Description
getAllVariants(array $cases = []) Expand branching into Variant[]
getAllVariables(): string[] Collect all substitution variable names
setValues(array $values): self Replace named variables with Text literals
replaceVariableName(string $from, string $to): self Rename a variable throughout
replaceRecursive(array $replace): self Substitute Pattern placeholders with Types fragments
quote(): self Wrap non-Pattern elements as Text (adds ICU escaping)
map(callable): self Transform each element
filter(callable): self Keep elements matching predicate
getVariables(): self Return only ICUTypeVariableInterface elements

ICU element classes

Every element in a Types sequence implements ICUTypeInterface:

ICUTypeInterface (Stringable)
├── Pattern          — raw unescaped text fragment
├── Text             — ICU-quoted literal (single-quoted in the format string)
├── Variable         — simple substitution {name} or # (inside plural)
├── AbstractSelect   — branching constructs
│   ├── Select
│   ├── Plural
│   └── SelectOrdinal
├── Number           — {var, number, skeleton}
├── Date             — {var, date, format}
├── Time             — {var, time, format}
├── SpellOut         — {var, spellout}
├── Ordinal          — {var, ordinal}
└── Duration         — {var, duration}

All element classes are final readonly — once constructed they are immutable.

Variant — a flat message branch

Variant is one linear path through a branching message:

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Variant;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Types;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Pattern;

$variant = new Variant(
    types: new Types([new Pattern('He liked this.')]),
    cases: ['select' => ['gender' => 'male']],
);

echo (string) $variant->types; // He liked this.
print_r($variant->cases);      // ['select' => ['gender' => 'male']]

cases is a map of SelectTypeName → variableName → choice that identifies which branch each Select/Plural/SelectOrdinal took to reach this variant. A choice is the option name ('male', 'one', '=0') or, for the other branch, the list of options it excludes (['male', 'female']). The list makes two selectors over the same variable combine correctly ({a, select, x {…}} … {a, select, x {…}} never yields the impossible "x in the first, other in the second" variant). null is still accepted as an empty list.

Cases — flattened variant set

Cases bundles the flat Types[] list together with a variator — a Types tree of Pattern placeholders that records how to reconstruct the original branching structure.

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Cases;

// $cases->types    — array of Types, one per flat variant
// $cases->variator — Types tree with Pattern placeholders

Parsing ICU strings

use EugeneErg\ICUMessageFormatParser\Parser;

$parser = new Parser();

// Simple variable
$types = $parser->parse('Hello {name}!');

// Plural
$types = $parser->parse('{count, plural, one {# item} other {# items}}');

// Select
$types = $parser->parse('{gender, select, male {He} female {She} other {They}}');

// SelectOrdinal
$types = $parser->parse('{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}');

// Number with skeleton
$types = $parser->parse('{price, number, ::currency/EUR .00}');

// Date with format
$types = $parser->parse('{ts, date, long}');

// Date with skeleton
$types = $parser->parse('{ts, date, ::yMMMd}');

// Nested
$types = $parser->parse(
    '{gender, select, ' .
    '  male   {{count, plural, one {He has # item} other {He has # items}}} ' .
    '  other  {{count, plural, one {They have # item} other {They have # items}}}' .
    '}'
);

The parser is extensible — you can register custom type classes:

$parser = new Parser(classes: [
    ...Parser::DEFAULT_CLASSES,
    'mytype' => MyCustomType::class,
]);

Building messages programmatically

All element classes have a static create() factory and can also be constructed directly:

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\{
    Types, Pattern, Variable, Text,
    Select, Plural, SelectOrdinal,
    Number, Date, Time, SpellOut, Duration, Ordinal,
    DateTimeFormat,
};
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\{
    Skeleton, Currency, Format, PrecisionFraction, Sign, Grouping,
};

// ── Literal text ──────────────────────────────────────────────────────────

$pat  = new Pattern('Hello ');           // unescaped; {, } will break ICU
$text = new Text("it's fine");          // auto-escaped to ICU 'it''s fine'
$var  = new Variable('name');            // {name}
$hash = new Variable('#');               // # (plural offset placeholder)

// ── Select ────────────────────────────────────────────────────────────────

$select = Select::create('gender', [
    'male'   => [new Pattern('He')],
    'female' => [new Pattern('She')],
    'other'  => [new Pattern('They')],
]);
// → {gender, select, male {He} female {She} other {They}}

// ── Plural ────────────────────────────────────────────────────────────────

$plural = Plural::create('count', [
    'one'   => [new Pattern('1 item')],
    'other' => [new Variable('#'), new Pattern(' items')], // # → {count}
]);
// → {count, plural, one {1 item} other {# items}}

// Exact-match cases
$plural2 = Plural::create('n', [
    '=0'    => [new Pattern('none')],
    '=1'    => [new Pattern('one')],
    'other' => [new Pattern('many')],
]);

// ── SelectOrdinal ─────────────────────────────────────────────────────────

$ordinal = SelectOrdinal::create('place', [
    'one'   => [new Pattern('1st')],
    'two'   => [new Pattern('2nd')],
    'few'   => [new Pattern('3rd')],
    'other' => [new Pattern('#th')],
]);

// ── Number ────────────────────────────────────────────────────────────────

// Default (no formatting options)
$num = Number::create('amount');
// → {amount, number}

// With skeleton tokens
$num = Number::create('price', ['::', 'currency/EUR', '.00']);
// → {price, number, ::currency/EUR .00}

// With strongly-typed Skeleton object
$num = new Number('price', new Skeleton(
    format:    new Currency('EUR'),
    sign:      Sign::Always,
    precision: new PrecisionFraction(2, 2),
    grouping:  Grouping::Min2,
));

// ── Date / Time ───────────────────────────────────────────────────────────

$date = new Date('created', DateTimeFormat::Long);
// → {created, date, long}

$date = new Date('created', 'yMMMd');          // skeleton
// → {created, date, ::yMMMd}

$time = new Time('ts', DateTimeFormat::Short);
// → {ts, time, short}

// ── Simple formatting types ───────────────────────────────────────────────

$spellout = new SpellOut('amount');    // {amount, spellout}
$duration  = new Duration('elapsed'); // {elapsed, duration}
$ordType   = new Ordinal('rank');     // {rank, ordinal}

// ── Composing a full message ──────────────────────────────────────────────

$message = new Types([
    new Variable('name'),
    new Pattern(' has '),
    Plural::create('count', [
        'one'   => [new Pattern('1 new message')],
        'other' => [new Variable('#'), new Pattern(' new messages')],
    ]),
    new Pattern(' as of '),
    new Date('date', DateTimeFormat::Medium),
]);

echo (string) $message;
// {name} has {count, plural, one {1 new message} other {# new messages}} as of {date, date}

Flattening branching messages

typesToCases() expands every select/plural/selectordinal branch into a flat list of linear message variants. Use this for:

  • Generating all possible message translations
  • Static analysis / QA of ICU messages
  • Feeding individual strings into external translation tools
  • Rendering every path for screenshot/visual testing
use EugeneErg\ICUMessageFormatParser\Parser;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Variant;

$parser = new Parser();
$types  = $parser->parse(
    '{gender, select, male {He} female {She} other {They}} '
  . '{count, plural, one {liked 1 post} other {liked # posts}}.'
);

$cases = $parser->typesToCases($types);

foreach ($cases->types as $i => $variant) {
    echo "[$i] " . (string) $variant, PHP_EOL;
}
// [0] He liked 1 post.
// [1] He liked {count, number} posts.
// [2] She liked 1 post.
// [3] She liked {count, number} posts.
// [4] They liked 1 post.
// [5] They liked {count, number} posts.

You can supply a custom key-maker to give variants meaningful names:

$cases = $parser->typesToCases($types, function (Variant $variant, string $defaultKey): string {
    $parts = [];
    foreach ($variant->cases as $type => $vars) {
        foreach ($vars as $varName => $branch) {
            $parts[] = $varName . '=' . (\is_string($branch) ? $branch : 'other');
        }
    }
    return implode('|', $parts) ?: $defaultKey;
});
// Keys: "gender=male|count=one", "gender=male|count=other", …
// The same keys are used in $cases->types and in the variator.

Accessing variant metadata

Each Variant carries the cases array showing which branch it took:

foreach ($cases->types as $variant) {
    // $variant is a Types object, $cases->types is Types[]

    // To get the branch labels you need to call getAllVariants on the original Types
}

$variants = $types->getAllVariants();
foreach ($variants as $variant) {
    echo (string) $variant->types, PHP_EOL;
    // $variant->cases = ['select' => ['gender' => 'male'], 'plural' => ['count' => 'one']]
    print_r($variant->cases);
}

Rebuilding from cases

casesToTypes() turns a (possibly edited or translated) set of variants back into one message. How the message is built is a strategy (Assembler\CasesAssemblerInterface); two are provided.

Compact rebuilding (default)

MinimalCasesAssembler factors the variants like a polynomial:

  1. text shared by all variants is taken out of every selector;
  2. if only a leading or trailing piece depends on a selector and the rest does not, a small selector is emitted for that piece only — A × B whole sentences become A + B fragments;
  3. otherwise the variants are split by the selector that gives the shortest result;
  4. options identical to other are dropped, selectors that change nothing disappear.

Words are never cut ({g, select, male {He} …}, not {…{H}…{Sh}}e) and # never leaves its plural.

$parser = new Parser();
$cases  = $parser->typesToCases($parser->parse(
    '{gender, select, male {He} female {She} other {They}} liked {count, plural, one {1 post} other {# posts}}.'
));

echo $parser->casesToTypes($cases);
// {gender, select, male {He} female {She} other {They}} liked {count, plural, one {1 post} other {# posts}}.

The variants can be translated or edited before rebuilding — Cases is immutable, so create a new one:

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Cases;

$translated = new Cases(
    array_map(fn (Types $variant) => $parser->parse(myTranslate((string) $variant)), $cases->types),
    $cases->variator,
);

echo $parser->casesToTypes($translated);
// {gender, select, male {Он оценил} female {Она оценила} other {Они оценили}} {count, plural, one {1 пост} other {# постов}}.
Message Variants Tree Compact
gender × plural (above) 6 267 chars 106 (= original)
3 independent selects 8 294 95 (= original)
5 selectors (3·3·3·3·2) 162 5 260 191 (= original)
offset:1 party invitation (745 chars) 12 745 359

Finding the absolute minimum is NP-hard; the assembler is a memoised greedy search that evaluates every split order up to exhaustiveLimit selectors (default 4) and goes greedy above that. Typical messages take 0.5–5 ms; the 162-variant message above takes about 20 ms.

Tree rebuilding

TreeCasesAssembler puts every variant, as a whole sentence, into a leaf of the selector tree. It is predictable (one leaf per variant) but grows as the product of all options:

use EugeneErg\ICUMessageFormatParser\Assembler\TreeCasesAssembler;

echo $parser->casesToTypes($cases, new TreeCasesAssembler());
// {count, plural, one {{gender, select, male {He liked 1 post.} …}} other {{gender, select, male {He liked {count, number} posts.} …}}}

Custom strategy

use EugeneErg\ICUMessageFormatParser\Assembler\CasesAssemblerInterface;

$parser = new Parser(assembler: new TreeCasesAssembler()); // default for this parser
$parser->casesToTypes($cases, new MyAssembler());          // or per call

Both assemblers throw InvalidMessageException when a variant referenced by the variator is missing, and both preserve option order, offset:N and the kind of every selector.

The # sign

The library follows ICU4C / php-intl:

  • # is the formatted number only at the top level of a plural/selectordinal option;

  • inside a nested select it is a literal character ({n, plural, other {{g, select, other {#}}}} prints #);

  • {n} cannot be used where n is also a plural argument (intl reports U_ARGUMENT_TYPE_MISMATCH), so rebuilt messages reference it as {n, number};

  • a literal # moved into a plural option by a rebuild is quoted ('#').

  • in flat variants # becomes {n, number}, which intl formats exactly like # (1,000, 1 000, 1,5 depending on the locale); a plain {n} would print the raw value (1000, 1.5). Rebuilding turns it back into #;

  • with offset:N, # shows value − N, which {n, number} cannot express either. Flat variants therefore keep it as {n, plural, offset:N other {#}} — valid ICU on its own, so a variant formats exactly like its branch — and rebuilding turns it back into #:

    $types = $parser->parse('{guests, plural, offset:1 =0 {nobody} other {you and # others}}');
    echo $types->getAllVariants()[1]->types; // you and {guests, plural, offset:1 other {#}} others

When building programmatically, an unquoted # in a Pattern passed to Plural::create() is the number, exactly as in parsed messages.

Verifying equivalence

Verification\EquivalenceChecker (requires ext-intl) formats two messages with every combination of sample values that reaches each branch — every select option plus an unknown one, numbers hitting every CLDR plural category, every =N (with and without offset) — and reports the first difference:

use EugeneErg\ICUMessageFormatParser\Verification\EquivalenceChecker;

$checker = new EquivalenceChecker();

$checker->areEquivalent($original, (string) $rebuilt, 'en'); // bool

$difference = $checker->firstDifference(
    '{n, plural, one {# item} other {# items}}',
    '{n, plural, other {# items}}',
);
echo $difference?->describe(); // {"n":1}: expected '1 item', got '1 items'

Own sample values can be passed as the 4th argument; above maxCombinations (default 20 000) the grid is sampled evenly.

Number formatting skeletons

Skeleton is a strongly-typed representation of an ICU Number Skeleton. All fields are optional and default to the ICU default value. The __toString() output is the canonical minimal skeleton string — no redundant tokens are emitted.

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\Skeleton;

$sk = new Skeleton(); // all defaults
echo (string) $sk;   // "" — empty skeleton = default decimal format

Format

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\Format;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\Currency;
use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\MeasureUnit;

new Skeleton(Format::Decimal);      // default, emits nothing
new Skeleton(Format::Integer);      // "integer"
new Skeleton(Format::Percent);      // "percent"
new Skeleton(Format::Permille);     // "permille"
new Skeleton(Format::BaseUnit);     // "base-unit"
new Skeleton(new Currency());       // "currency"  (USD default)
new Skeleton(new Currency('EUR'));   // "currency/EUR"
new Skeleton(new MeasureUnit('length-meter')); // "::measure-unit/length-meter"
new Skeleton(new MeasureUnit('speed-kilometer-per-hour', 'duration-hour'));
// "::measure-unit/speed-kilometer-per-hour per-measure-unit/duration-hour"

Notation

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\{
    Notation, ScientificNotation, EngineeringNotation, ScientificOptions,
};

new Skeleton(notation: Notation::Standard);       // default, emits nothing
new Skeleton(notation: Notation::NotationSimple); // "::notation-simple"
new Skeleton(notation: Notation::CompactShort);   // "::compact-short"
new Skeleton(notation: Notation::CompactLong);    // "::compact-long"
new Skeleton(notation: new ScientificNotation()); // "::scientific"
new Skeleton(notation: new EngineeringNotation(new ScientificOptions())); // "::engineering"

// Scientific with options
new Skeleton(notation: new ScientificNotation(
    new ScientificOptions(
        exponentSign:      Sign::Always,  // → /sign-always
        minExponentDigits: 2,             // → /*ee
    )
));
// "::scientific/sign-always/*ee"

// Concise forms parsed (both read and write):
//   E0   → ScientificNotation
//   E00  → ScientificNotation(minExponentDigits=2)
//   EE0  → EngineeringNotation
//   K    → CompactShortNotation
//   KK   → CompactLongNotation

Sign display

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\Sign;

new Skeleton(sign: Sign::Auto);               // default, emits nothing
new Skeleton(sign: Sign::Always);             // "::sign-always"  (+! concise)
new Skeleton(sign: Sign::Never);              // "::sign-never"   (+_ concise)
new Skeleton(sign: Sign::Accounting);         // "::sign-accounting"
new Skeleton(sign: Sign::AccountingAlways);   // "::sign-accounting-always"
new Skeleton(sign: Sign::ExceptZero);         // "::sign-except-zero" (+? concise)
new Skeleton(sign: Sign::AccountingExceptZero); // "::sign-accounting-except-zero"
new Skeleton(sign: Sign::Negative);           // "::sign-negative"
new Skeleton(sign: Sign::AccountingNegative); // "::sign-accounting-negative"

Precision

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\{
    Precision, PrecisionFraction, PrecisionSignificant, PrecisionIncrement,
};

// Named precision
Precision::Integer;          // "precision-integer"
Precision::Unlimited;        // "precision-unlimited"
Precision::CurrencyStandard; // requires Currency format
Precision::CurrencyCash;     // requires Currency format

// Fraction precision
new PrecisionFraction(minFraction: 2, maxFraction: 2);        // ".00"
new PrecisionFraction(0, 2);                                   // ".##" (default)
new PrecisionFraction(2, null);                                // ".00*" (unlimited)
new PrecisionFraction(2, 2, trailingZeroHideIfWhole: true);   // ".00/w"

// Combined fraction + significant
new PrecisionFraction(
    minFraction:         0,
    maxFraction:         2,
    minSignificantDigits: 3,
    maxSignificantDigits: null,  // unlimited
);
// ".##/@@@*"

// Significant digits
new PrecisionSignificant(minDigits: 3, maxDigits: 3);          // "@@@"
new PrecisionSignificant(minDigits: 1, maxDigits: 3);          // "@##"
new PrecisionSignificant(minDigits: 3, maxDigits: null);       // "@@@*"
new PrecisionSignificant(3, 3, trailingZeroHideIfWhole: true); // "@@@/w"

// Increment precision
new PrecisionIncrement(0.05);  // "precision-increment/0.05"
new PrecisionIncrement(0.5);   // "precision-increment/0.5"
new PrecisionIncrement(50);    // "precision-increment/50"

Grouping

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\Grouping;

Grouping::Auto;       // default
Grouping::Off;        // "group-off"   (,_ concise)
Grouping::Min2;       // "group-min2"  (,? concise)
Grouping::OnAligned;  // "group-on-aligned" (,! concise)
Grouping::Thousands;  // "group-thousands"

Integer width

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\IntegerWidth;

new Skeleton(integerWidth: IntegerWidth::fromConcise(3));
// Serialises as "000" (concise form) → at least 3 integer digits

new Skeleton(integerWidth: new IntegerWidth(zeroFillTo: 1, truncateAt: 3));
// "::integer-width/##0"

IntegerWidth::trunc();
// "integer-width-trunc" — truncate all integer digits

new Skeleton(integerWidth: new IntegerWidth(zeroFillTo: 0, truncateAt: null));
// "::integer-width/*"

Rounding mode

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\RoundingMode;

new Skeleton(roundingMode: RoundingMode::HalfUp);
// "::rounding-mode-half-up"

// All modes:
// Ceiling, Floor, Down, Up, HalfEven, HalfDown, HalfUp, Unnecessary

Scale

new Skeleton(scale: 100.0);  // "::scale/100"
new Skeleton(scale: 0.01);   // "::scale/0.01"

// Special case: Percent + scale/100 → concise %x100
new Skeleton(format: Format::Percent, scale: 100.0); // "%x100"

Unit width

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\UnitWidth;

UnitWidth::Short;    // default
UnitWidth::Narrow;   // "::unit-width-narrow"
UnitWidth::FullName; // "::unit-width-full-name" (Currency or MeasureUnit)
UnitWidth::IsoCode;  // "::unit-width-iso-code"  (Currency only)
UnitWidth::Hidden;   // "::unit-width-hidden"     (Currency only)

Currency

new Skeleton(new Currency('EUR'));
// Minimal: "currency/EUR"

new Skeleton(new Currency('USD'));
// Minimal: "currency"  (USD is the special-cased default)

new Skeleton(
    format:    new Currency('JPY'),
    unitWidth: UnitWidth::FullName,
    precision: Precision::CurrencyCash,
);
// "::currency/JPY unit-width-full-name precision-currency-cash"

Measure units

new Skeleton(new MeasureUnit('length-meter'));
// "::measure-unit/length-meter"

new Skeleton(new MeasureUnit('speed-meter-per-second'));
// "::measure-unit/speed-meter-per-second"

new Skeleton(
    format:    new MeasureUnit('length-meter', perUnit: 'duration-second'),
    unitWidth: UnitWidth::FullName,
    precision: new PrecisionFraction(1, 2),
);
// "::measure-unit/length-meter per-measure-unit/duration-second unit-width-full-name .0#"

Numbering system

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\NumberingSystem;

new Skeleton(numberingSystem: new NumberingSystem('latin'));  // "::latin"
new Skeleton(numberingSystem: new NumberingSystem('arab'));   // "::numbering-system/arab"
new Skeleton(numberingSystem: new NumberingSystem('deva'));   // "::numbering-system/deva"

Decimal separator

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\Number\DecimalSeparator;

DecimalSeparator::Auto;   // default, emits nothing
DecimalSeparator::Always; // "::decimal-always"

Multi-token skeletons

Tokens are space-separated. The serialiser always emits the minimal canonical form:

$sk = Skeleton::createFromOptions(['currency/EUR', 'sign-always', 'group-min2', '.00']);
echo (string) $sk;
// "::currency/EUR group-min2 sign-always .00"

// Round-trip: parse a skeleton string
$sk = Skeleton::createFromOptions(
    preg_split('/\s+/', 'compact-short sign-always @@@')
);
echo (string) $sk;
// "::compact-short sign-always @@@"

Date and Time formatting

use EugeneErg\ICUMessageFormatParser\DataTransferObjects\{Date, Time, DateTimeFormat};

// Named formats
new Date('ts', DateTimeFormat::Short);   // {ts, date, short}
new Date('ts', DateTimeFormat::Medium);  // {ts, date}  (Medium is default, omitted)
new Date('ts', DateTimeFormat::Long);    // {ts, date, long}
new Date('ts', DateTimeFormat::Full);    // {ts, date, full}

// Skeleton strings (passed after "::")
new Date('ts', 'yMMMd');   // {ts, date, ::yMMMd}
new Date('ts', 'yMMMMd');  // {ts, date, ::yMMMMd}

// Same API for Time
new Time('ts', DateTimeFormat::Short);   // {ts, time, short}
new Time('ts', 'HHmmss');               // {ts, time, ::HHmmss}

Utility methods

Quoting text

Parser::quote() escapes a raw string for safe inclusion in an ICU pattern:

$parser = new Parser();

echo $parser->quote("This {must} be 'escaped'");
// This '{must}' be ''escaped''

Getting all variable names

$vars = $types->getAllVariables();
// ['name', 'count', 'gender', …]

Replacing variable names

// Replace '#' with 'count' throughout (what Plural::create does internally)
$types = $types->replaceVariableName('#', 'count');

Substituting values

// Substitute variables with literal values (produces ICU-quoted Text nodes)
$result = $types->setValues(['name' => 'Alice', 'city' => 'Paris']);
// Variables become Text nodes; serialised with ICU single-quote escaping

replaceRecursive

Replace Pattern placeholder nodes with arbitrary Types fragments. This is how TreeCasesAssembler fills the variator:

$variator   = new Types([new Pattern('0'), new Pattern(' and '), new Pattern('1')]);
$flatTypes  = [
    new Types([new Pattern('one')]),
    new Types([new Pattern('two')]),
];
$result = $variator->replaceRecursive($flatTypes);
echo (string) $result; // "one and two"

Supported ICU element types

ICU syntax Class Notes
{var} Variable Simple substitution
{var, select, …} Select String-keyed branching
{var, plural, …} Plural CLDR plural categories + =N exact match
{var, selectordinal, …} SelectOrdinal Ordinal plural categories
{var, number} Number Default decimal format
{var, number, ::skeleton} Number + Skeleton Full ICU skeleton
{var, number, pattern} Number + Message Legacy decimal pattern
{var, date} Date Medium date (default)
{var, date, short|medium|long|full} Date + DateTimeFormat Named date format
{var, date, ::skeleton} Date Date skeleton
{var, time, …} Time Same options as Date
{var, spellout} SpellOut Spell-out number
{var, ordinal} Ordinal Ordinal number
{var, duration} Duration Duration formatting
'quoted text' Text ICU single-quoted literal
Raw text Pattern Unquoted text fragment

Apostrophes follow ICU (ApostropheMode::DOUBLE_OPTIONAL, the default of ICU and PHP intl): a single ' starts quoted text only before a syntax character — { or }, and # inside a plural option. So Don't stop and It's {name}'s turn are plain text, '{'literal'}' is a literal brace, and '' is always one apostrophe.

Plural case keywords

Keyword Meaning
zero CLDR zero category
one CLDR one (singular) category
two CLDR two category
few CLDR few category
many CLDR many category
other Fallback (always required)
=N Exact numeric match

Error handling

Every exception thrown by the library implements EugeneErg\ICUMessageFormatParser\Exceptions\ExceptionInterface. Message problems are reported as InvalidMessageException (an InvalidArgumentException, so code that caught LogicException keeps working):

use EugeneErg\ICUMessageFormatParser\Exceptions\ExceptionInterface;
use EugeneErg\ICUMessageFormatParser\Exceptions\InvalidMessageException;

try {
    $parser->parse('{unclosed');
} catch (InvalidMessageException $e) {
    // 'Invalid ICU message "{unclosed": Unexpected end of input at line 1, column 10, expected "," or "}".'
    // the parser error (line, column, expected) is $e->getPrevious(), an EugeneErg\PegParser\Exceptions\ParseException
}

$parser->parse('{x, select, a {1} a {2} other {3}}'); // Duplicate option key "a".
$parser->parse('{g, gender}');                        // Unknown argument type "gender".
Select::create('g', ['male' => [new Pattern('He')]]); // The "select" argument "g" requires an "other" option.
Plural::create('n', ['lots' => [new Pattern('x')]]);  // Invalid option "lots".
$parser->casesToTypes(new Cases([], $variator));      // No variant for case "0".

Value objects of number skeletons validate themselves with InvalidArgumentException / LogicException:

Skeleton::createFromOptions(['totally-unknown-xyz']);                         // Unknown skeleton token
new Skeleton(format: Format::Decimal, precision: Precision::CurrencyStandard); // precision-currency-* needs Currency
new IntegerWidth(zeroFillTo: 5, truncateAt: 2);                               // truncate < fill

Comparison with alternatives

Feature this library php-icu-message-formatter MessageFormatter (intl)
Parse → object tree ✅ ❌ ❌
Serialise back to ICU ✅ ❌ ❌
Flatten to variants ✅ ❌ ❌
Rebuild from variants (compact) ✅ ❌ ❌
Check two messages are equivalent ✅ (uses intl) ❌ ❌
Strongly-typed skeleton ✅ ❌ ❌
Round-trip lossless ✅ n/a n/a
Format at runtime ❌* ✅ ✅
PHP extension required ❌ ❌ ✅ (intl)
PHP 8.2+ types/enums ✅ ❌ n/a
Static analysis friendly ✅ partial ❌

*This library is a parser and transformer, not a formatter. Pair it with MessageFormatter (intl) or php-icu-message-formatter to actually format messages at runtime.

Recommended pairing

// 1. Parse & analyse/transform with this library
$parser  = new Parser();
$types   = $parser->parse($icuString);
$cases   = $parser->typesToCases($types); // flatten for translation tooling

// 2. Format at runtime with intl
$fmt = new MessageFormatter('en_US', $icuString);
echo $fmt->format(['count' => 3, 'name' => 'Alice']);

Architecture overview

ICU string
   │
   ▼ Parser::parse()
Types (tree: ICUTypeInterface[])
   │
   ├──── (string) cast ──────────────► canonical ICU string
   │
   ├──── getAllVariants() ───────────► Variant[]
   │                                     ├── types: Types   (flat message)
   │                                     └── cases: array   (branch labels)
   │
   ▼ Parser::typesToCases()
Cases
   ├── types:    Types[]  (one per flat variant)
   └── variator: Types    (Pattern placeholders)
   │
   ▼ Parser::casesToTypes()   — CasesAssemblerInterface: MinimalCasesAssembler (default) | TreeCasesAssembler
Types (rebuilt message)
   │
   ▼ (string) cast
canonical ICU string

Class hierarchy

Parser                            — parse / quote / typesToCases / casesToTypes (grammar loaded once)
Assembler/
├── CasesAssemblerInterface       — strategy of casesToTypes()
├── MinimalCasesAssembler         — compact rebuild (factoring)
├── TreeCasesAssembler            — whole variants in tree leaves
├── VariatorBuilder               — builds the selector tree of variant keys
├── VariatorLeaves                — reads variant keys and their choices from the variator
└── Minimal/ (@internal)          — Tokenizer, Row, Node, Factorizer, Renderer
Verification/
├── EquivalenceChecker            — compares two messages with php-intl
├── SampleValues                  — argument values reaching every branch
└── Difference                    — first mismatch found
Exceptions/
├── ExceptionInterface            — marker of all library exceptions
└── InvalidMessageException
DataTransferObjects/
├── Contracts/
│   ├── ICUTypeInterface          — base contract (Stringable + create + getAllVariants)
│   ├── ICUTypeVariableInterface  — getValue()
│   └── ICUTypeMergeInterface     — merge() (for adjacent Text/Pattern coalescing)
├── Types                         — immutable sequence of ICUTypeInterface
├── Variant                       — one flat branch (types + cases metadata)
├── Cases                         — flat variant set + variator
├── Pattern                       — raw text (implements ICUTypeMergeInterface)
├── Text                          — ICU-quoted literal (implements ICUTypeMergeInterface)
├── Variable                      — {name} or #
├── AbstractSelect                — base for branching types (getOptions / withOptions / mapOptions)
│   ├── Select
│   └── AbstractPluralSelect      — categories, =N, offset, `#` handling
│       ├── Plural
│       └── SelectOrdinal
├── Number
├── Date
├── Time
├── SpellOut
├── Duration
├── Ordinal
├── DateTimeFormat (enum)
├── Message                       — raw pattern/text sequence for format options
└── Number/
    ├── Skeleton
    ├── NumberNotation (abstract)
    │   ├── StandardNotation
    │   ├── NotationSimple
    │   ├── CompactShortNotation
    │   ├── CompactLongNotation
    │   ├── ScientificNotation
    │   └── EngineeringNotation
    ├── ScientificOptions
    ├── Format (enum)
    ├── Notation (enum)           — legacy; hierarchy classes are preferred
    ├── Sign (enum)
    ├── UnitWidth (enum)
    ├── Grouping (enum)
    ├── Precision (enum)
    ├── RoundingMode (enum)
    ├── DecimalSeparator (enum)
    ├── Currency
    ├── MeasureUnit
    ├── NumberingSystem
    ├── IntegerWidth
    ├── PrecisionFraction
    ├── PrecisionSignificant
    ├── PrecisionIncrement
    └── PrecisionFractional

Development

composer install
composer check      # pint --test + phpstan (level max, strict rules) + phpunit
composer fix        # apply code style (Laravel Pint, rules in pint.json)
composer coverage   # phpunit with a text coverage report (needs pcov or xdebug)
  • Code style — Laravel Pint with the full rule set in pint.json (PSR-12, PhpCsFixer and Symfony risky sets, strict imports/phpdoc rules).
  • Static analysis — PHPStan level: max, bleeding edge, phpstan-strict-rules, phpstan-phpunit, phpstan-deprecation-rules; no baseline and no ignores.
  • Tests — 600+ PHPUnit tests in random order, failing on warnings/notices/deprecations; ~99.5 % line coverage. Rebuilding is checked against php-intl on a corpus of real-life messages (tests/Assembler/MessageCorpus.php), so every assembler output is proven to format exactly like the source.
  • CI — GitHub Actions: full check on PHP 8.3 and 8.4 (PHPUnit 12 and Pint need 8.3+), syntax of the library on PHP 8.2.

Upgrade notes

  • The grammar is a PEG grammar of eugene-erg/peg-parser instead of eugene-erg/string-parser. A custom grammar file given to new Parser($parserPath) must return EugeneErg\PegParser\Grammar (see Template.php).

  • Parsing follows ICU (checked against php-intl on 40 000 messages): spaces around names, types and styles are allowed ({ n , number }); } outside of an argument and an apostrophe left open at the end are text; argument names may be Unicode ({имя}); an empty style ({d, date, }) is accepted.

  • Inside select, '# is plain text: an apostrophe quotes only before { and } there, # is special only in plural and selectordinal. Before, '#' in a select gave the text #.

  • Quoted text in a date, time or number style survives: {d, date, 'at' HH:mm} is parsed into Pattern and Text parts of Message and written back as is (before, {d, date, prefix 'quoted'} came back broken).

  • A custom style (Message) is written exactly as it was read, spaces included: intl keeps them in the formatter pattern, {n,number,#,##0.00} formats 3.00 and {n, number, #,##0.00} formats 3.00. A Message built in code is written right after the comma: new Message(new Pattern('MM/dd/yyyy')) gives {d, date,MM/dd/yyyy}; start the pattern with a space to get {d, date, MM/dd/yyyy}.

  • Parse errors say where and what was expected: Unexpected end of input at line 1, column 10, expected "," or "}".

  • A long text is read in one step: a 100 000-character message parses in under a millisecond (it took 0.6 s), the test corpus about twice as fast as before.

  • Parser::END is no longer used (deprecated).

  • Parser::casesToTypes() now returns the compact message by default. Pass new TreeCasesAssembler() (per call or to the constructor) for the previous layout. Both outputs are equivalent.

  • The other choice in Variant::$cases is the list of excluded options instead of null (null is still accepted on input).

  • typesToCases() with a custom $makeKey now keys Cases::$types with the same keys as the variator (before, variants kept numeric keys and could not be rebuilt).

  • # inside a select nested in a plural is a literal (as in ICU/intl); before it was bound to the select variable.

  • offset:N survives typesToCases() → casesToTypes().

  • # of a plural appears in flat variants as {n, number} instead of {n} (2.0.1), so a variant formats the number for the locale like the original.

  • # of a plural with offset:N appears in flat variants as {n, plural, offset:N other {#}} instead of {n}, so a variant formats with value − N like the original (before it showed the full value).

  • Select::create() without other throws InvalidMessageException instead of a PHP warning + TypeError.

  • AbstractSelect::getOptions() is public; new withOptions(), mapOptions(), getDimension(); Plural/SelectOrdinal share AbstractPluralSelect.

  • Parse errors are InvalidMessageException (still a LogicException).

License

MIT © Eugene Erg