nvl / primitives
Immutable application value objects, exact money, validation, and ISO reference catalogs for Laravel
Requires
- php: ^8.4
- ext-ctype: *
- ext-filter: *
- ext-json: *
- ext-mbstring: *
- brick/math: ^0.14 || ^0.15 || ^0.16 || ^0.17 || ^0.18
- brick/money: ^0.11 || ^0.14
- laravel/framework: ^13.0
- nesbot/carbon: ^2.72 || ^3.0
- nvl/core: ^7.0
Requires (Dev)
- giggsey/libphonenumber-for-php: ^9.0
- jschaedl/iban-validation: ^2.7
- larastan/larastan: ^3.10
- laravel/pint: ^1.27
- mockery/mockery: ^1.6
- orchestra/testbench: ^11.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- symfony/intl: ^7.0 || ^8.0
- symfony/polyfill-intl-icu: ^1.33
Suggests
- ext-intl: Enables locale-aware monetary formatting through Brick Money.
- giggsey/libphonenumber-for-php: Enables phone number validation and formatting (^9.0).
- jschaedl/iban-validation: Enables IBAN validation and formatting (^2.7).
- symfony/intl: Enables ISO country, currency, language, and locale reference data (^7.0 || ^8.0).
- symfony/polyfill-intl-icu: Enables Symfony Intl on PHP without ext-intl (^1.33).
Provides
None
Conflicts
None
Replaces
None
README
Quickstart
composer require nvl/primitives:^7.0
Required NVL dependencies: nvl/core (^7.0). Use immutable value objects for validated scalar values. No package model factory or database is required; invalid programmer input retains its native exception category.
use Nvl\Primitives\ValueObjects\EmailAddress; $email = EmailAddress::from('reader@example.com');
Use the event catalog and Testing your app below. The suite getting-started guide provides a complete Comments host fixture; package archives retain their own local references.
For support, open an issue. For vulnerabilities, use private reporting. See Contributing.
See the installation and publishing guide for Composer setup, configuration, migration ownership, and agent skills.
Quick reference
| Item | Value |
|---|---|
| Installed through | composer require nvl/primitives:^7.0 |
| Module identifier | nvl/primitives |
| PHP namespace | Nvl\Primitives |
| Service provider | Nvl\Primitives\Providers\PrimitivesServiceProvider |
| Configuration | config/nvl-primitives.php |
Immutable application value objects, exact money, Eloquent casts, validation rules, currency conversion, and standards-backed reference catalogs for Laravel 13.
Purpose and boundaries
Primitives replaces the reusable parts of a traditional application “Core” module without becoming a second application framework. It owns:
- immutable value objects and canonical serialization;
- Eloquent casts for scalar, JSON, and monetary values;
- exact money arithmetic and an exchange-rate provider boundary;
- international phone and IBAN parsing backed by maintained registries;
- current ISO country, currency, and language catalogs;
- application locale, city, and bank option boundaries;
- native scalar, array, and domain-value contracts for application-owned projections.
It does not own users, settings, authorization, controllers, application routes, UI components, live exchange-rate HTTP clients, or a global cities/banks database.
Requirements and installation
- PHP 8.4+
- Laravel 13
ext-mbstring,ext-json,ext-ctype, andext-filter- optional
ext-intlfor locale-aware money formatting
Brick Money/Math and Carbon are required. Install the optional registries for the capabilities your application calls:
composer require giggsey/libphonenumber-for-php:^9.0 jschaedl/iban-validation:^2.7 symfony/intl:'^7.0 || ^8.0' # On PHP without ext-intl, also install: composer require symfony/polyfill-intl-icu:^1.33
The package boots without these registries. Calling a dependent feature without its library throws an exception naming the package to install.
composer require nvl/primitives:^7.0 php artisan vendor:publish --tag=nvl-primitives-config php artisan vendor:publish --tag=nvl-primitives-translations php artisan vendor:publish --tag=nvl-primitives-skills
The package has no migrations and works without a database.
The translation tag publishes validation overrides to
lang/vendor/nvl-primitives while package defaults continue to load directly.
Value objects
| Value object | Canonical storage | Important behavior |
|---|---|---|
EmailAddress |
validated address string | normalizes the domain and masks for display |
Url |
absolute HTTP(S) string | normalizes scheme, host, and default ports; rejects credentials |
CountryCode |
ISO alpha-2 uppercase string | validates current country data |
CurrencyCode |
known ISO 4217 uppercase string | name, symbol, and fraction digits |
LocaleCode |
normalized BCP 47 core tag | enforces language, script, region, then variants |
PhoneNumber |
E.164 string | international parsing and formatting |
Iban |
electronic IBAN string | country format/checksum and masking |
DateTimeValue |
Y-m-d\TH:i:s.u\Z |
strict RFC 3339 input and canonical UTC output |
Percentage |
exact decimal ratio | exact percentage calculations |
Weight |
exact grams | kilograms, pounds, and ounces |
Length |
JSON metres | explicit scale and rounding for unit conversion |
Coordinates |
JSON string coordinates | WGS84 validation and distance |
PostalAddress |
JSON object | international components with an optional postal code |
Money |
{"minor":"…","currency":"…"} |
exact arithmetic and explicit conversion rounding |
Every primitive is immutable, JSON serializable, stringable, and type-safe for equality.
EmailAddress and Url follow PHP's native ASCII email/URL validation policy. They do not perform IDNA conversion or accept internationalized email local parts. Convert internationalized domains to reviewed punycode and percent-encode non-ASCII URL components in the host before construction; use an application-owned value policy when SMTPUTF8 is required.
Eloquent casts
Declare the value-object class directly:
protected function casts(): array { return [ 'email' => EmailAddress::class, 'phone' => PhoneNumber::class, 'coordinates' => Coordinates::class, 'price' => Money::class, ]; }
Scalar primitives use one string/decimal column. Coordinates, PostalAddress, and default Money use JSON. Null remains null; malformed persisted values fail during hydration.
Scalar cast assignment and ValidPrimitive accept strings and integers, preserving exact values. Booleans and input floats are rejected before coercion. Database-hydrated floats remain supported by scalar casts where the primitive permits them; use string columns when exact decimal storage is required.
Money storage
Default JSON contains only integer minor units and currency:
{"minor":"1999","currency":"EUR"}
For an explicitly fixed-currency schema:
protected function casts(): array { return [ 'price_minor' => Money::class.':minor,EUR', 'price_decimal' => Money::class.':decimal,EUR', ]; }
Scalar modes accept a Money instance or a scalar in the declared units. The cast expects the configured currency. JSON also supports an explicit currency with Money::class.':json,EUR'. Dirty checks compare money, not stored text: reassigning an equal amount keeps the model clean whatever the JSON spacing or key order (for example from PostgreSQL jsonb) or decimal padding of the stored value. Structured JSON primitives such as Coordinates compare the same way.
Use Money::class.':decimal,record,price_minor' on price when the model stores both decimal and minor values. The populated minor column is authoritative, including zero. Writes update both columns and assigning null clears both. Use Money::class.':minor,record,price_minor' for a model attribute backed only by price_minor. An optional fourth argument explicitly names the decimal column; leave it empty to keep the default. Add the fifth argument strict to make the minor column the only source, as in Money::class.':decimal,EUR,price_minor,,strict': hydration never falls back to the decimal, throws when a query selects the decimal without the minor column, and rejects a null minor column beside a non-null decimal. Without strict, a null minor column still falls back to the decimal. Record currency comes from HasRecordCurrency::getRecordCurrency() or the model's raw currency attribute. Bind RecordCurrencyResolver to map another source, such as an eager-loaded parent.
SQLite hydrates DECIMAL columns as floating-point values. Decimal-mode casts normalize only those database-hydrated floats to the currency's fraction digits; assigning a float remains invalid. Prefer JSON or fixed-currency minor-unit storage when amounts may exceed SQLite's exact numeric range.
Exact money
Construct with decimal strings or integer minor units—never floats:
use Brick\Math\RoundingMode; use Nvl\Primitives\Services\MoneyFormatter; use Nvl\Primitives\ValueObjects\Money; $price = Money::of('19.99', 'EUR'); $shipping = Money::minor(500, 'EUR'); $total = $price->add($shipping); // EUR 24.99 $triple = $price->multiply(3); // EUR 59.97 $share = $price->divide(3, RoundingMode::HalfUp); $total->amount(); // "24.99" $total->minorAmount(); // "2499" $total->currency(); // CurrencyCode("EUR") $formatter->format($total, 'de-DE'); // locale-aware with ext-intl
Currency is always explicit. An unrepresentable amount or operation requires a suitable rounding mode. Arithmetic requires matching currencies. MoneyFormatter uses its injected configuration repository and returns exact amount currency text when native ext-intl is unavailable or the minor units exceed the formatter's safe precision.
Conversion chains keep their original exact value through Money::source(). Use withSource() when rehydrating separately persisted provenance. The canonical toArray() payload represents the current value.
Arithmetic carries the source amount along. add() and subtract() combine source amounts in the same source currency and drop provenance when the source currencies differ; no rate is ever invented. multiply(), divide(), absolute() and negate() apply the same operation to the source amount, rounding at the source currency's scale with the same rounding mode, so an inexact source result throws under the default RoundingMode::Unnecessary. allocate() and split() divide each side separately with the same ratios or parts and pair the pieces by position; each side conserves its own minor units, so a piece's effective rate may differ slightly.
MoneyStorage::prepare() selects a storage amount and currency through StoragePolicy. Preserve converts to the record currency and requires explicit rounding for inexact conversion. Adopt returns the input currency for the host to persist with the amount. Require demands a currency match. MigrateParent signals a required parent update through ParentCurrencyMigrationRequired. The application owns persistence and any parent migration.
MoneyPresenter::present() returns amount, cents, currency and formatted, with optional recordCurrency, recordCents and pair. Pass PresentationOptions to select the locale or supply an explicit record or paired value. The exact numeric fields are strings by default. Pass new PresentationOptions(numeric: true) to receive amount as a float and cents, recordCents and the pair's cents as integers; minor units beyond JavaScript's safe integer range (±9007199254740991) throw InvalidPrimitive. The numeric amount is for display only; keep cents for exact work. Applications own their DTO conversions.
Currency conversion
Configure deterministic rates:
'exchange_rates' => [ 'implementation' => ConfiguredExchangeRateProvider::class, 'rates' => [ 'EUR/USD' => '1.10', 'EUR/BGN' => '1.95583', ], ],
$usd = $converter->convert( money: Money::of('100.00', 'EUR'), target: 'USD', roundingMode: RoundingMode::HalfUp, );
Rates mean “target major units for one source major unit.” Every direction must be configured explicitly; inverse rates are never inferred. Rate values must be positive decimal strings, not floats or booleans. Optional as_of and max_age_seconds metadata must be supplied together; future, stale, malformed, and missing rates fail explicitly.
For production rates, implement and bind ExchangeRateProvider. It may use a database/API but must return an auditable decimal string and respect the optional effective date. Network calls do not belong in Money or CurrencyConverter.
Phones and IBANs
$phone = PhoneNumber::fromRegion('044 668 18 00', 'CH'); (string) $phone; // +41446681800 $phone->international(); // +41 44 668 18 00 $phone->national(); // 044 668 18 00 $phone->rfc3966(); // tel:+41-44-668-18-00 $phone->region(); // CountryCode("CH") $iban = Iban::from('DE89 3704 0044 0532 0130 00'); $iban->storageValue(); // DE89370400440532013000 $iban->formatted(); $iban->masked(); $iban->country(); // CountryCode("DE")
National phone input requires an explicit region or nvl-primitives.phone.default_region. Prefer an explicit request-specific region.
Locale and ISO codes
$country = CountryCode::from('bg'); // BG $currency = CurrencyCode::from('eur'); // EUR $locale = LocaleCode::from('zh_hans_cn'); // zh-Hans-CN $country->name('en'); $currency->symbol('de'); $currency->fractionDigits(); $locale->language(); $locale->script(); $locale->regionCode(); // alpha country or numeric UN M49 region $locale->region();
Locale tags support a language followed by an optional script, optional alpha/numeric region, and valid variant subtags. Extensions and private-use subtags are intentionally outside the package contract. Application-supported locale options come from Core’s Nvl\Support\Contracts\LocaleCatalog. Configure nvl-core.locales or bind that contract in the host.
Exact quantities and structured values
$discount = Percentage::fromPercent(20); $discount->decimal(); // "0.2" $discount->of('125.00'); // "25" $discount->ofRounded( '125.00', 2, RoundingMode::HalfUp, ); // "25.00" $weight = Weight::kilograms('1.5'); $weight->inGrams(); // "1500.000" $weight->inOunces(); // "52.911" $length = Length::from('12', 'in'); $length->in('cm', 2, RoundingMode::Unnecessary); // "30.48" $sofia = Coordinates::from('42.6977', '23.3219'); $plovdiv = Coordinates::from('42.1354', '24.7453'); $sofia->distanceTo($plovdiv); // kilometres $sofia->googleMapsUrl();
Decimal input may use scientific notation with at most three exponent digits (1.5e3); a larger exponent such as 1e999999999 is rejected as InvalidPrimitive instead of being expanded in memory.
PostalAddress keeps components separate for country-specific presentation and permits countries without postal codes. DateTimeValue accepts only timezone-qualified RFC 3339 input with valid offset hours and minutes, preserves microseconds, and stores one canonical UTC value; convert only at display boundaries. Coordinate arrays accept numeric strings, integers, or floats and reject booleans. Email normalization preserves the complete local part, including quoted @ characters, and lowercases only the domain.
Use DateTimeCast::class.':timestamp,UTC' for SQL timestamps without offsets and DateTimeCast::class.':timestamptz,UTC' for offset-aware storage. Use column precision 6 to keep microseconds. A named storage timezone for a bare timestamp requires an unambiguous wall time. Add the third argument carbon to hydrate CarbonImmutable directly. Dirty checks compare instants, so reassigning a value equal to the stored one keeps the model clean whatever offset, fraction padding or PostgreSQL session time zone the stored text uses.
Implement ReferenceDirectory in the host for record-backed references that have database IDs. Its find() and bounded search() return the record identity, display label and scalar metadata. ReferenceCatalog remains available for ISO and configured lookups.
Implement the optional ReferenceCodeDirectory extension instead when records also have a stable code; it adds findByCode(). A host binds an Eloquent-backed directory like this:
use App\Models\Warehouse; use InvalidArgumentException; use Nvl\Primitives\Contracts\ReferenceCodeDirectory; use Nvl\Primitives\Contracts\ReferenceDirectory; use Nvl\Support\Contracts\TextMatcher; final class WarehouseDirectory implements ReferenceCodeDirectory { public function __construct(private readonly TextMatcher $text) {} public function find(string $catalog, string $id): ?array { return $catalog === 'warehouses' && ctype_digit($id) ? $this->record(Warehouse::query()->whereKey($id)->first()) : null; } public function findByCode(string $catalog, string $code): ?array { return $catalog === 'warehouses' ? $this->record(Warehouse::query()->where('code', $code)->first()) : null; } public function search(string $catalog, ?string $query = null, int $limit = 50): array { if ($limit < 1 || $limit > 100) { throw new InvalidArgumentException('The reference search limit must be between 1 and 100.'); } if ($catalog !== 'warehouses') { return []; } $term = trim($query ?? ''); $warehouses = Warehouse::query(); if ($term !== '') { $warehouses->where(function ($builder) use ($term): void { $builder->setQuery($this->text->contains($builder->getQuery(), 'name', $term)); $builder->setQuery($this->text->contains($builder->getQuery(), 'code', $term, boolean: 'or')); }); } return $warehouses ->orderBy('name')->orderBy('id') ->limit($limit) ->get() ->map(fn (Warehouse $warehouse): array => $this->record($warehouse)) ->all(); } private function record(?Warehouse $warehouse): ?array { return $warehouse === null ? null : [ 'id' => (string) $warehouse->getKey(), 'code' => $warehouse->code, 'label' => $warehouse->name, 'metadata' => ['active' => $warehouse->active], ]; } } // In a service provider $this->app->bind(ReferenceDirectory::class, WarehouseDirectory::class); $this->app->bind(ReferenceCodeDirectory::class, WarehouseDirectory::class);
Core's TextMatcher matches % and _ literally and folds case on PostgreSQL and SQLite; always use the builder it returns. Keep search() bounded and ordered.
Url validates URL syntax and represents private or loopback hosts too. It supplies no DNS, redirect, network allowlist or SSRF protection; remote fetchers must enforce those policies separately. EmailAddress likewise does not establish deliverability or a public destination.
Laravel validation
'email' => [ 'required', new ValidPrimitive(EmailAddress::class, 'email address'), ], 'iban' => [ 'nullable', new ValidPrimitive(Iban::class, 'IBAN'), ], 'phone' => [ 'required', new ValidPhoneNumber('BG'), ],
Validation messages ship in English and Bulgarian and use Laravel's translation pipeline. Request validation improves messages, but domain code should still construct the primitive before persistence.
Reference catalogs
ReferenceCatalog returns bounded arrays with code, label, and scalar metadata keys:
$countries = $catalog->countries('Bulg', 'en', 20); $currencies = $catalog->currencies('Euro', 'en'); $languages = $catalog->languages('Bulgarian', 'en'); $locales = $catalog->locales('bg', 'en'); $countryCode = $countries[0]['code'];
Countries, currencies, and languages come from installed Symfony Intl standards data. Locale labels include script and region qualifiers so supported variants remain distinguishable. Cities and banks are deployment-specific, so configure small application lists:
'reference' => [ 'cities' => [ 'sofia-bg' => [ 'label' => 'Sofia', 'country' => 'BG', 'region' => 'Sofia City', ], ], 'banks' => [ 'UNCRBGSF' => [ 'label' => 'UniCredit Bulbank', 'country' => 'BG', ], ], ],
Each entry is keyed by its code. Numeric codes such as bank routing numbers are returned as strings; a list without codes is rejected. Malformed catalog entries and limits outside 1..250 fail immediately. Large or dynamic datasets belong in an application service or repository. Primitives intentionally avoids mandatory reference tables and seeders.
Application projections
Use Money::toArray(), Length::toArray(), Coordinates::toArray(), and PostalAddress::toArray() at application boundaries. The application owns any DTOs, API resources, and generated TypeScript types. Keep vendor library objects out of JSON responses.
Adoption
- Replace existing money values only after auditing every float construction and making rounding explicit.
- Replace custom locale/country/currency enums or casts with validated codes.
- Replace phone/IBAN regex and checksum logic with registry-backed objects.
- Keep settings in
nvl/settings; Primitives does not own settings. - Retain application reference tables only when persistence, translation, or domain metadata is necessary.
- Replace suggestion controllers with application controllers calling
ReferenceCatalogor an application-owned directory.
Audit data before changing cast modes. JSON, decimal, and minor-unit money columns require an explicit migration.
Quality
composer install composer quality
The package gate runs Pint, PHPStan at maximum strictness, and isolated Testbench/Pest tests. Local Dagger verification additionally runs dependency analysis, Composer audit, integration tests and PHP 8.4/Laravel 13 release checks.
See UPGRADING.md, SECURITY.md, CONTRIBUTING.md, and CHANGELOG.md.
Supported PHP usage
The source @api declarations identify supported services, extension contracts, and value types. Public members marked @internal and untagged implementation types remain package-owned.
Testing your app
Immutable currencies, money, percentages, units, formatters, and catalogs are
direct APIs. This package has no Eloquent models or factories. Test calculations
with native values and substitute only the existing ExchangeRateProvider when
an application needs an exchange-rate boundary.
use Brick\Math\RoundingMode; use Nvl\Primitives\Contracts\ExchangeRateProvider; use Nvl\Primitives\Services\CurrencyConverter; use Nvl\Primitives\ValueObjects\CurrencyCode; use Nvl\Primitives\ValueObjects\Money; $rates = Mockery::mock(ExchangeRateProvider::class); $rates->shouldReceive('rate')->once() ->withArgs(fn (CurrencyCode $from, CurrencyCode $to, $at): bool => (string) $from === 'EUR' && (string) $to === 'USD' && $at === null) ->andReturn('1.10'); $this->app->instance(ExchangeRateProvider::class, $rates); $money = Money::of('10.00', 'EUR'); $converted = $this->app->make(CurrencyConverter::class) ->convert($money, 'USD', RoundingMode::HalfUp); expect($converted->amount())->toBe('11.00');
The configured default already uses a conditional transient binding and retains
host replacements. A host HTTP-backed rate provider can use Http::fake() in
its integration tests. Direct value tests and the injected rate test require no
new symmetry interface, package fake, or database fixture.
In Laravel application tests, register a native Mockery interface mock or a small
implementation with $this->app->instance(Contract::class, $substitute) before
resolving your application service. A host binding installed before package
registration is retained; later contract replacements affect subsequent
resolutions. Rebuild previously resolved host services after replacing their
dependencies. Mocks exercise your application orchestration;
package authorization, persistence, and external effects need real integration
tests.
ExchangeRateProvider already retains host bindings through bindIf. Immutable value construction and calculations remain direct; no new interface or factory is introduced.
Configuration and responses
Use nvl-primitives configuration and canonical package environment names. The consumer owns HTTP validation, response mapping and frontend types. Keep validated value objects and the existing exchange-rate provider boundary native.
Error codes and events
All recognized package failures implement Nvl\Support\Contracts\PackageException; only RespondableException opts into safe response metadata. Keep native PHP programmer errors and Laravel/SDK exceptions distinct. The optional PackageExceptionRenderer is registered by the host in withExceptions; it leaves unrelated, marker-only and non-JSON handling to the host. Its JSON envelope is {message:string, code:string, context:object}. Request locale is host-owned; diagnostics/previous exceptions are not public copy. Event schemas and source connections are documented in events.
The table lists enum discriminators, including any successful codes retained for compatibility. A code is not itself an HTTP status; the throwing exception's suggestedStatus() is authoritative, especially legacy/custom constructors. Empty context renders as {}; only documented JSON-safe context is presented.
| Code | Suggested status | Public context | Translation key |
|---|---|---|---|
operation_failed |
Exception-defined; see suggestedStatus() |
Declared safe scalar/array map; otherwise {} |
nvl-primitives::responsecode.operation_failed |
exchange_rate_stale |
409 | Declared safe scalar/array map; otherwise {} |
nvl-primitives::responsecode.exchange_rate_stale |
exchange_rate_unavailable |
422 | Declared safe scalar/array map; otherwise {} |
nvl-primitives::responsecode.exchange_rate_unavailable |
License
Released under the MIT License.
Shared service contracts, model extensions and composition apply alongside the package-specific rules above.