john-wink / en16931-php
A dependency-free, Java-free PHP validator for EN 16931 electronic invoices (ZUGFeRD / Factur-X / XRechnung, CII and UBL) — full KoSIT rule coverage in pure PHP.
Requires
- php: ^8.4
- ext-bcmath: *
- ext-dom: *
- ext-libxml: *
Requires (Dev)
- laravel/pint: ^1.18
- pestphp/pest: ^4.0
- pestphp/pest-plugin-type-coverage: ^4.0
- phpstan/phpstan: ^2.0
- rector/rector: ^2.5
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main / 0.4.x-dev
- v0.4.1
- v0.4.0
- v0.3.2
- v0.3.1
- v0.3.0
- v0.2.0
- v0.1.0
- dev-task/01a145ed-a895-en16931-changelog-abschnitt-unreleased-a
- dev-task/01a145c5-5fa3-en16931-folge-r6d-hmac-der-tabelle-ungue
- dev-task/01a1454a-f01f-en16931-neuzuschnitt-pr-5-ab-720388e66f8
- dev-task/01a144af-271f-en16931-folge-pr-4-mb-funktionen-mit-fes
- dev-task/01a14460-1998-en16931-folge-pr-3-r3-s3-minors-vor-rele
- dev-task/01a14444-b3aa-en16931-folge-pr-2-r2c-s2c-minors-vor-re
- dev-task/01a143fd-fda5-en16931-valueerror-bei-betraegen-mit-lee
- dev-task/01a143ca-734a-en16931-br-co-17-offizielle-cen-toleranz
- dev-task/kai-env-example-fuer-arbeitsbaeume
- dev-rule-fixes-and-coverage
This package is auto-updated.
Last update: 2026-10-16 18:35:01 UTC
README
A dependency-free, Java-free PHP validator for EN 16931 e-invoices (ZUGFeRD / Factur-X / XRechnung), in both CII and UBL syntax.
The official EN 16931 / KoSIT rule sets are XSD schemas plus Schematron compiled to XSLT 2.0 and run by Saxon (Java). This library reimplements the full three-stage pipeline natively in PHP — XSD schema, then the syntax rules (UBL-CR/SR, CII-SR/DT), then the business rules — with no JRE, no jar downloads and no subprocess, reading amounts as exact decimal strings (BCMath) so the tolerance-free calculation rules are exact.
Important
Every layer the KoSIT validator configuration enforces (validator-configuration-xrechnung 3.0.2 — the legal conformance target for XRechnung in Germany) is covered: the XSD schemas, all 1276 syntax rules (UBL-CR/SR, CII-SR/DT) and 274 / 274 business rules across EN 16931 core, the VAT categories, calculations, decimals, code lists and the German BR-DE / BR-DEX CIUS. Coverage is measured against that configuration and proven bidirectionally against the official KoSIT validator over its full test suite (see COVERAGE.md and the conformance section below). This is a best-effort reimplementation, not certified software — do not treat a green result as a legal guarantee.
Requirements
- PHP 8.4+,
ext-bcmath,ext-dom
Install
composer require john-wink/en16931-php
Usage
use JohnWink\En16931\En16931Validator; // validate() auto-detects CII vs UBL; validateCii()/validateUbl() force one. $result = En16931Validator::xrechnung()->validate($xml); // or ::en16931() $result->isValid(); // bool — no fatal violation foreach ($result->violations as $violation) { echo "{$violation->ruleId} [{$violation->flag}]: {$violation->message}\n"; }
You can also validate a pre-built model (En16931Validator::…->validateModel($invoice))
without XML.
Model inputs are UTF-8. Every string in an Invoice passed to validateModel()
must be UTF-8 encoded, whatever mb_internal_encoding() is set to: the engine
trims values as UTF-8 and does not convert other encodings. The XML readers
always deliver UTF-8.
validateModel() fails closed on a broken contract: every string in the model
that is not valid UTF-8 is a fatal violation with the rule ID UTF-8, flagged
with the path of the field (seller.name, notes[1],
lines[0].attributes[0].value). Strings in values outside the model classes,
such as other objects or nested lists, are checked as well: every property of
such an object, private and protected ones included, and the string of a
Stringable. The violation is flagged with [?] after the field instead of
their keys (thirdPartyPayments[0][?]). The check stops at 64 levels and
after 1,000,000 counted values. It skips a model object it has checked before
without a violation, and a list with the same entries as the last list without
a violation in the same property of the same model class, unless that list
holds lists. Comparing with that list weighs one unit per entry plus the bytes
of its string entries and string keys; up to 64 units the comparison is free,
above that its weight counts on every comparison, whether the list is the same
array or a content-equal one built apart. The same rule holds for a string that
is not valid UTF-8: every further place with the same content, whether the same
string or a content-equal one stored apart, weighs its bytes; up to 64 bytes it
is free, above that its weight counts. The check recognises that content by an
HMAC-SHA256 under a secret it draws anew for every check and never returns, so
no sender can choose strings that collide in its table. In the lists of every
model object other
than the invoice, an entry counts unless it is a model object the check meets
for the first time; a model object with a violation that the check meets again
there counts with all its values. Every value outside the model classes counts,
including list entries skipped as a reference already checked. The result for a
model whose lists hold up to 64 units, whose model objects each appear once or
whose lines share model objects, and whose invalid strings of more than 64 bytes
each appear once, therefore does not depend on its size. A list
of more than 64 units counts its weight even when the comparison fails, so lines
with different lists count as well: lines that each hold 65 distinct model
objects end with the limit violation after about 15,400 lines. Lines that hold
different lists of the same model objects count these model objects, and many
model objects that share a longer list end with the limit violation. Every
violation is reported, without a cap on their number, so memory grows with the
violations: in the worst case a small model with a shared subtree and a list of
invalid strings yields close to 1,000,000 violations with paths of several
hundred characters, measured at about 1.1 GB (969,099 violations, paths up to
444 characters) and estimated at up to about 2 GB with longer property names in
the path. A model beyond these limits, or a model object that contains
itself, is a fatal violation with the rule ID UTF-8 and a message of its own
(… is nested too deep or too large to be checked for valid UTF-8., … contains itself and cannot be checked for valid UTF-8.), even when every
string is valid UTF-8. The result then holds only these violations: the business
rules do not run, so no message repeats the raw bytes. A single-byte no-break
space (0xA0 in ISO-8859-1), for example, never counts silently as a filled
field. The engine does not convert other encodings; convert them with
mb_convert_encoding() before you build the model.
Rule coverage
Validation pipeline
Validation runs the three stages the official KoSIT validator applies — natively in PHP, no Java:
| Stage | Checks | Rules | Status |
|---|---|---|---|
| 1 — XSD schema | Structure of UBL 2.1 Invoice/CreditNote & CII D16B | — | ✅ bundled |
| 2 — Syntax rules | UBL-CR/SR & CII-SR/DT code-list, cardinality & datatype restrictions | 1276 | ✅ 1276 / 1276 |
| 3 — Business rules | EN 16931 core + XRechnung CIUS/Extension | 274 | ✅ 274 / 274 |
Stage 2 breakdown: UBL-CR 679, UBL-SR 50, CII-SR 450, CII-DT 97. Evaluated directly against the DOM by SchematronEngine from resources/syntax-rules.json — proven against the KoSIT validator over the full official instance suite (0 false positives).
Business rules
274 of 274 rules implemented (0 partial, 0 open) — measured against the validator-configuration-xrechnung 3.0.2 (release 2025-03-21), the compiled Schematron the official KoSIT validator runs (and the parity oracle). The full per-rule matrix lives in COVERAGE.md.
| Rule group | ✅ | 🟡 | ❌ | Total |
|---|---|---|---|---|
| BR — core document & line rules | 60 | 0 | 0 | 60 |
| BR-CO — conditions & calculations | 25 | 0 | 0 | 25 |
| BR-DEC — decimals | 21 | 0 | 0 | 21 |
| BR-CL — code lists | 23 | 0 | 0 | 23 |
| BR-AE — Reverse charge | 10 | 0 | 0 | 10 |
| BR-IG — IGIC (Canary Islands) | 10 | 0 | 0 | 10 |
| BR-IP — IPSI (Ceuta/Melilla) | 10 | 0 | 0 | 10 |
| BR-IC — Intra-community supply | 12 | 0 | 0 | 12 |
| BR-S — Standard rated | 10 | 0 | 0 | 10 |
| BR-Z — Zero rated | 10 | 0 | 0 | 10 |
| BR-E — Exempt from VAT | 10 | 0 | 0 | 10 |
| BR-G — Export outside the EU | 10 | 0 | 0 | 10 |
| BR-O — Not subject to VAT | 14 | 0 | 0 | 14 |
| BR-B — Split payment (Italy) | 2 | 0 | 0 | 2 |
| BR-DE — XRechnung CIUS | 32 | 0 | 0 | 32 |
| BR-DEX — XRechnung Extension | 15 | 0 | 0 | 15 |
| Total | 274 | 0 | 0 | 274 |
Full ISO 4217 and ISO 3166-1 code lists are bundled. Document-level allowances and charges (BG-20/BG-21) are modelled and reconciled.
The matrix is generated from the rule sets themselves — after adding a rule, run:
php tools/generate-coverage.php # regenerates COVERAGE.md + this summary
tests/Feature/CoverageDocTest.php fails the suite when the docs drift from
the code, and tools/build-rules-reference.php rebuilds the reference list from
the KoSIT validator configuration (the same artefacts the parity test runs
against), so the coverage denominator is exactly what the official validator
enforces.
The Clean Vehicles Directive profile (BR-DE-CVD-*) is implemented too but lives under "Implemented beyond the reference" in COVERAGE.md: it is a separate KoSIT scenario, not part of the standard XRechnung configuration, and is enforced only for CVD-profile invoices.
Conformance / parity with KoSIT
The results are proven against the official KoSIT validator (the Java
reference: validator 1.5.0 + validator-configuration-xrechnung 3.0.2), used as a
dev/CI oracle — never shipped or required at runtime. tests/Feature/ParityTest.php
runs the entire official KoSIT test suite (every UBL and CII instance across
the standard, extension and technical-cases groups) through both this
library and KoSIT — across all three layers (XSD, syntax rules and business
rules) — and asserts:
- verdict parity — accept/reject agrees on every instance, and
- no false positives — every rule this library fires (BR-*, UBL-CR/SR, CII-SR/DT), KoSIT fired too.
Reproduce it (needs a JRE):
bash tools/kosit-setup.sh # downloads the KoSIT jar + config to build/kosit/
vendor/bin/pest tests/Feature/ParityTest.php
A second, Java-free check asserts this library fatally rejects none of the
official positive instances — so the normal suite stays meaningful even without
a JRE. The Java-backed parity tests skip automatically when Java or the KoSIT
tools are absent; CI (.github/workflows/ci.yml) sets Java up and runs the full
bidirectional comparison on every push.
The oracle repeatedly paid for itself: it caught an incomplete BT-3 code list, several rule-id drifts against the shipped configuration (the Leitweg-ID is BR-DE-15, IGIC/IPSI are BR-IG/BR-IP), and rules present in the schematron source but not enforced by the configuration (BR-DE-TMP-32) — each of which would otherwise have rejected invoices the official validator accepts.
Quality gates
composer qa # pint + rector + phpstan (max) + pest
License
MIT. See LICENSE.md.