Search by

msstc4php / vo-base

maxim.shamaev@gmail.com

Immutable value objects for PHP 8.4+, with no framework dependencies.

Package info

github.com/msstc4php/vo-base

pkg:composer/msstc4php/vo-base

Statistics

Installs: 18

Dependents: 13

Suggesters: 0

Stars: 0

Open Issues: 0

v1.4.1 2026-11-24 04:39 UTC

This package is auto-updated.

Last update: 2026-11-28 15:05:12 UTC


README

Immutable, self-validating value objects for PHP 8.4+ with zero runtime dependencies. Framework integration lives in separate packages, so this one stays a plain library.

Install

Not on Packagist yet, so register the GitHub repository first:

composer config repositories.vo-base vcs https://github.com/msstc4php/vo-base
composer require msstc4php/vo-base:^1.0

Requires PHP 8.4 and ext-bcmath (Decimal compares with bccomp()).

Optional, for arithmetic on Decimal and Percentage:

composer require brick/math

Without it those methods throw MissingDependencyException; construction and comparison still work.

Design

Every value object is a final readonly class that validates in its constructor and throws a typed exception on invalid input — there is no partially-valid state. Validation lives in one place per type, so anything built on top — a Doctrine type, a form constraint — reuses it rather than restating it.

use MSSTC4PHP\ValueObject\Network\Ipv4Address;

$ip = Ipv4Address::from('192.168.0.1'); // throws InvalidIpv4Exception on bad input
Ipv4Address::tryFrom('nope');           // null instead of throwing
Ipv4Address::isValid('192.168.0.1');    // bool
(string) $ip;                            // '192.168.0.1'
$ip->equals(Ipv4Address::from('192.168.0.1')); // true

The construction convention mirrors BackedEnum: from() (throws), tryFrom() (nullable), isValid() (bool).

Beyond validation, value objects carry immutable domain behavior — every operation returns a new instance and never mutates in place:

use MSSTC4PHP\ValueObject\Network\Cidr;
use MSSTC4PHP\ValueObject\Network\IpAddress;

$block = Cidr::from('10.0.0.0/8');
$block->contains(IpAddress::from('10.1.2.3'));   // true
IpAddress::from('10.1.2.3')->isPrivate();         // true

use MSSTC4PHP\ValueObject\Network\IpRange;
IpRange::from('10.0.0.5-10.0.0.20')->toCidrs();   // 10.0.0.5/32, 10.0.0.6/31, 10.0.0.8/29, ...

use MSSTC4PHP\ValueObject\Finance\Decimal;        // needs brick/math
Decimal::from('1')->divide('3', 4);               // Decimal('0.3333')

Arithmetic on Decimal/Percentage is delegated to brick/math (optional); without it, those types still construct, compare, and serialize, but arithmetic throws MissingDependencyException. Network math (Cidr, IpRange, IP predicates) is dependency-free.

isPublic() is not an SSRF gate. It is a syntactic classification of the address value (excludes private, loopback, link-local, multicast, and IANA special-purpose ranges). It does not resolve DNS, cannot see DNS-rebinding, and may lag the IANA registries. Use a dedicated egress-filtering layer for SSRF defense. Likewise, Cidr::hostCount() throws for IPv6 blocks of /65 or wider (the count exceeds PHP's integer range); Cidr::addressCount() and IpRange::addressCount() return the exact count as a decimal string.

Test data

Testing\RandomValueObjects generates valid instances for your own tests and property-style checks; pass a seed to make a run reproducible within one release (a new release may draw different values for the same seed):

use MSSTC4PHP\ValueObject\Testing\RandomValueObjects;

$random = new RandomValueObjects(seed: 42);
$random->ipRange();        // e.g. 41.12.7.200-198.51.3.9
$random->iban();           // a DE IBAN with a valid checksum
$random->currencyCode();   // always one with ISO minor units

Catalogue

Group Value objects
Network Ipv4Address, Ipv6Address, IpAddress, MacAddress, Eui64, Oui, Hostname, DomainName, Port, UrlScheme, UrlPath, Uri, Url, QueryString, QueryParameter, Cidr, IpRange, HttpMethod
Identity EmailAddress, Uuid (validate, version detect, v4()/v7()/v7Now())
i18n / geo CountryCode, CurrencyCode, LanguageCode (ISO enums), Locale, Latitude, Longitude, GeoCoordinates
Finance Iban, Bic, CreditCardNumber (Luhn, deprecated for PaymentCardNumber in msstc4php/vo-finance), Decimal (arbitrary precision)
Temporal TimeOfDay, Duration (ISO 8601), DateRange
Primitives NonEmptyString, BoundedString, PositiveInt, NonNegativeInt, IntRange, Percentage
Format Slug, HexColor, Base64String, JsonString, PhoneNumber, SemVer, ClassString

Full money handling is delegated to brick/money: pair CurrencyCode with Brick\Money\Money. CurrencyCode::isoMinorUnits() is the value monetary arithmetic needs; displayFractionDigits() is CLDR formatting and the two disagree for 25 codes (15 of them in current use).

Iban enforces the length and BBAN character pattern of every country in the SWIFT IBAN Registry (the ISO 13616 registration authority) and reads the bank and branch identifiers from the registry's positions; a country absent from the registry keeps the generic check. SWIFT's terms do not allow redistributing the registry, so src/Support/IbanRegistry.php embeds only those structural facts, generated by tools/generate-iban-registry.php from a copy of the TXT edition you download yourself. The source and its terms are in docs/sources/IBAN.md.

CountryCode, CurrencyCode, and LanguageCode are string-backed enums generated at build time and committed, so they carry no runtime dependency. Regenerate after a data update:

php tools/generate-iso-enums.php

Storage form

Payload\ValueObjectMapper turns a value object into what a column or a wire format holds, and back. Framework bridges are built on it, and it is the place to start when you write one of your own:

use MSSTC4PHP\ValueObject\Payload\ValueObjectMapper;

$mapper = new ValueObjectMapper();
$mapper->toPayload(EmailAddress::from('a@example.com'));   // 'a@example.com'
$mapper->toPayload(new IntRange(1, 5));                     // ['min' => 1, 'max' => 5]
$mapper->fromPayload(Port::class, '8080');                  // Port 8080: numeric strings from PDO are accepted

String-backed value objects map to strings, int- and float-backed ones to numbers, the ISO enums to their codes, and the composites (BoundedString, IntRange, GeoCoordinates, DateRange) to flat arrays through a Payload\PayloadCodec; pass your own codecs to the constructor for your own composites, or a package's whole set through its Payload\ProvidesCodecs class (vo-documents: new ValueObjectMapper(Codecs::all())). An abstract class is mapped only when it implements Contract\ResolvesConcreteClass and declares its own from(), which builds the one subclass the value fits: the column holds the value, and the fitting subclass comes back. A wrong type or shape throws InvalidPayloadException, invalid content the value object's own exception; both extend InvalidValueObjectException.

Use fromPayload() for storage your application wrote and fromUntrustedPayload() for request input. The latter refuses classes whose codec implements Payload\TrustedSourceOnly: a BoundedString payload carries its own length limits, so a client could send its own maxLength. supportsUntrusted() tells a bridge up front.

Payloads are read strictly: integers as canonical digit strings ("080" is rejected), floats as plain decimals, DateRange boundaries only as ISO 8601 instants with an offset.

Framework integration

The core carries no framework dependency, and deptrac fails the build if one appears. Integration lives in separate packages, all built on the same storage form (Payload\ValueObjectMapper), so a value written by one reads back through another:

Package What it gives you
msstc4php/vo-base-doctrine 40 Doctrine field types per branch (ORM and MongoDB ODM), plus money embeddables that aggregate in SQL
msstc4php/vo-base-bundle Symfony: Validator constraints, Serializer normalizer, route argument resolver, and the Doctrine types from one line in bundles.php
msstc4php/vo-base-laravel Laravel 13.40+: Eloquent cast, validation rule, $request->valueObject(), form-request helper, route parameters
msstc4php/vo-base-yii2 Yii 2: validator, ActiveRecord behavior, model values, action parameters
msstc4php/vo-base-codeigniter4 CodeIgniter 4: Entity and Model casts, validation rule, validated data, controller arguments
msstc4php/vo-base-cycle Cycle ORM 2: typecast handler
msstc4php/vo-base-spiral Spiral 3: filter caster, route argument interceptor, vo:valid checker (storage via vo-base-cycle)

Install whichever you need; none is required by this package, and each pulls in only the stack it actually bridges.

Separate from the bridges, domain packages build on this one, each with a Doctrine bridge of its own: msstc4php/vo-gs1 (GS1 keys, element strings, Digital Link, UDI), msstc4php/vo-finance (securities identifiers, card numbers, payment QR), msstc4php/vo-identifiers (publication, transport, telecom, chemistry, trade and energy identifiers) and msstc4php/vo-documents (identity documents and personal names). Their value objects go through the framework bridges like the ones here.

The package family

Every package follows semantic versioning; its README has a "Backward compatibility" section saying what a minor may and may not change. Releases as of 2026-11-27 (UTC):

Package Release Requires Gives you
msstc4php/vo-base 1.4.1 PHP 8.4, ext-bcmath the core: scalar, money, identity, network, geo and time value objects, the payload mapper
msstc4php/vo-base-doctrine 1.3.0 vo-base ^1.2 Doctrine ORM / MongoDB ODM types and embeddables for the core
msstc4php/vo-base-bundle 1.3.0 (1.x), 2.2.0 (2.x) vo-base ^1.1 (2.x: ^1.4), Symfony 7.4 / 8 Symfony constraints, normalizer, argument resolver; registers the Doctrine types of the core and of every installed domain bridge
msstc4php/vo-base-laravel 1.0.0 vo-base ^1.4, Laravel 13.40+ Eloquent cast, validation rule, request input, route parameters
msstc4php/vo-base-yii2 1.0.0 vo-base ^1.4, Yii 2.0.55+ validator, ActiveRecord behavior, model values, action parameters
msstc4php/vo-base-codeigniter4 1.0.0 vo-base ^1.4, CodeIgniter 4.7.4+ Entity/Model casts, validation rule, validated data, controller arguments
msstc4php/vo-base-cycle 1.0.0 vo-base ^1.4, Cycle ORM 2.10+ typecast handler
msstc4php/vo-base-spiral 1.0.0 vo-base ^1.4, Spiral 3.18+ filter caster, route argument interceptor, vo:valid checker
msstc4php/vo-gs1 1.2.0 vo-base ^1.4 GS1 keys, element strings, Digital Link, EPC URIs, UDI, NDC, Russian and EU marking codes
msstc4php/vo-gs1-doctrine 1.0.0 vo-gs1 ^1.0, vo-base-doctrine ^1.3 Doctrine types for vo-gs1
msstc4php/vo-identifiers 2.0.0 vo-base ^1.4, vo-gs1 ^1.0 publication, transport, telecom, chemistry, trade and energy identifiers
msstc4php/vo-identifiers-doctrine 1.1.0 vo-identifiers ^1.0 || ^2.0, vo-base-doctrine ^1.3 Doctrine types for vo-identifiers
msstc4php/vo-documents 1.3.0 vo-base ^1.4 identity documents and personal names, ICAO 9303 Latin names
msstc4php/vo-documents-doctrine 1.0.0 vo-documents ^1.0, vo-base-doctrine ^1.3 Doctrine types for vo-documents
msstc4php/vo-finance 1.2.0 vo-base ^1.4 securities identifiers, payment card numbers, payment QR payloads
msstc4php/vo-finance-doctrine 1.0.0 vo-finance ^1.0, vo-base-doctrine ^1.3 Doctrine types for vo-finance

Every bridge converts through the core's Payload\ValueObjectMapper, so the domain value objects work in every framework bridge without a package of their own: a domain package plus the bridge of your framework is enough. Only Doctrine needs a per-domain package (the -doctrine bridges), because each Doctrine type is a class of its own.

Getting started

Until the packages are on Packagist, register each one you install as a VCS repository, as in "Install" above (composer config repositories.<name> vcs https://github.com/msstc4php/<name>), including the ones it requires.

  • Symfony with Doctrine: msstc4php/vo-base-bundle, msstc4php/vo-base-doctrine, the domain packages you need and their -doctrine bridges. Add the bundle to bundles.php; it registers every installed type (domain_types: false turns the domain ones off), and the constraints work for domain value objects too.
  • Laravel: msstc4php/vo-base-laravel and the domain packages; the service provider is auto-discovered.
  • Yii 2, CodeIgniter 4, Spiral (+ Cycle): the bridge of your framework and the domain packages; each README shows the configuration.
  • Composite values of a domain package (for example vo-documents' names, which store a JSON object): give the mapper the package's codec set, new ValueObjectMapper(\MSSTC4PHP\ValueObject\Documents\Codecs::all()), through your framework's container (each bridge README has the binding; the Symfony bundle takes codec_providers on 2.x).
  • Plain PHP: the core and the domain packages need no framework at all.

Development

make check   # php -l, PHPStan level max, cs-fixer, composer validate/audit, Rector, deptrac
make test    # PHPUnit
make fix     # apply cs-fixer + rector

License

MIT.