sirix / object-mapper
Framework-neutral object-to-object mapper with generated PHP mappers.
Requires
- php: ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0
Requires (Dev)
- bamarni/composer-bin-plugin: ^1.8
- phpunit/phpunit: ^11.5
README
sirix/object-mapper is a dependency-free mapper for explicit, trusted
object -> object boundaries. It compiles registered conventional mappings to
small PHP classes that use public source reads and a target's public
constructor.
Installation
composer require sirix/object-mapper
The package requires PHP 8.2 or later and has no production dependencies.
Register and map a pair
use Sirix\ObjectMapper\Contract\ObjectMapperInterface; use Sirix\ObjectMapper\Definition\MappingDefinition; use Sirix\ObjectMapper\Generator\MapperCache; use Sirix\ObjectMapper\Generator\PhpMapperGenerator; use Sirix\ObjectMapper\Metadata\MappingMetadataFactory; use Sirix\ObjectMapper\Runtime\MappingRegistry; use Sirix\ObjectMapper\Runtime\ObjectMapper; use Sirix\ObjectMapper\Runtime\ValueTransformerRegistry; $registry = new MappingRegistry([ new MappingDefinition(UserResult::class, UserDto::class), ]); $transformers = new ValueTransformerRegistry([ new UuidToString(), new DateTimeToAtom(), ]); /** @var ObjectMapperInterface $mapper */ $mapper = new ObjectMapper( $registry, new MapperCache( new MappingMetadataFactory($transformers, mappingRegistry: $registry), new PhpMapperGenerator(), __DIR__ . '/var/cache/object-mapper', generateOnDemand: false, valueTransformerRegistry: $transformers, mappingRegistry: $registry, ), ); /** @var UserDto $dto */ $dto = $mapper->map($result, UserDto::class);
Register a pair once in application wiring. Mapping always uses the exact
runtime source class and requested target class; an unregistered pair raises
MappingNotRegistered.
Optional Cycle ORM direct-proxy matching
Exact runtime-source matching remains the default. If an application has explicitly registered a Cycle ORM entity pair and wants to accept Cycle's runtime direct proxy for that entity too, opt in for that individual direct definition:
use Sirix\ObjectMapper\Definition\CustomMappingDefinition; use Sirix\ObjectMapper\Definition\MappingDefinition; use Sirix\ObjectMapper\Definition\SourceMatchMode; new MappingDefinition( Package::class, PackageDto::class, sourceMatch: SourceMatchMode::CycleProxy, ); new CustomMappingDefinition( Package::class, PackageDto::class, $packageMapper, SourceMatchMode::CycleProxy, );
This does not enable general inheritance or polymorphic mapping. It accepts a
concrete Package as usual, or only a value that implements Cycle's
EntityProxyInterface and whose immediate parent is exactly Package.
Normal subclasses, indirect proxies, and proxies for other entities remain
rejected. ProviderCustomMappingDefinition remains exact-only.
The package does not require Cycle ORM: the interface is detected at runtime only when this opt-in is selected. Mapping does not preload relations or alter Cycle lazy loading, so applications remain responsible for query preloading and avoiding N+1 queries before mapping.
Generated-mapper cache format 6 includes this choice. Release 0.8.0
retains format 6; generated files remain owner-only (0600).
Customize a conventional mapping
Keep DTOs independent of this package by defining exceptional source-member
selection at registration time. A MapRule takes precedence over the usual
same-name property/getter convention:
use Sirix\ObjectMapper\Definition\MapRule; use Sirix\ObjectMapper\Definition\MappingDefinition; $definition = new MappingDefinition( UserResult::class, UserDto::class, rules: [ 'id' => MapRule::from('uuid'), 'email' => MapRule::fromGetter('getPrimaryEmail'), 'externalId' => MapRule::fromMethod('identifier') ->through(UuidToString::class), 'createdAt' => MapRule::fromMethod('createdAt') ->through(DateTimeToAtom::class), 'kind' => MapRule::constant('external'), 'enabled' => MapRule::constant(true), 'rank' => MapRule::constant(0), 'note' => MapRule::constant(null), ], ignoredSource: ['passwordHash'], );
MapRule::from() selects exactly a public, non-static, typed source property;
it never falls back to a getter. MapRule::fromGetter() selects exactly a
public, non-static, zero-argument get*() method with a declared return type.
MapRule::fromMethod() selects a deliberately named public, non-static,
zero-argument method with a declared return type; it does not extend
conventional method discovery. through() accepts exactly one registered
transformer class after a source selector. The transformer is checked during
warmup: its transform() method must have one typed required parameter and a
typed non-void result, and its input/output types must be compatible with the
source member and target parameter.
Transformer instances belong in one application-owned registry shared by the metadata factory and cache. The registry uses exact runtime classes only: it does not instantiate classes, resolve services, or consult a framework container. Transformations are explicit and type-checked; the mapper never performs implicit casts.
MapRule::constant() is a source-less terminal rule for trusted, fixed DTO
values. It accepts only null, bool, int, finite float, and string;
the value must be exactly compatible with the target constructor type during
warmup. Numeric strings, booleans, null, and integers are never coerced to a
different scalar type. A constant neither reads nor maps a same-named public
source property, so that property must still be selected by another rule or be
listed in ignoredSource.
Constants are compiled into generated cache PHP. Register only non-secret,
non-request-controlled application configuration: never put passwords, tokens,
ciphertext/plaintext, or personal data in a constant. constant() cannot be
combined with through(), nested(), or collection(). There is deliberately
no conditional rule, expression language, callback, property path, dynamic
method call, or service lookup; use a typed transformer for a trivial derived
value and an application-owned custom mapper for policy, authorization,
redaction, decryption, I/O, or stateful behavior.
The conventional is*() lookup remains available only for boolean target
parameters. Every public source property must be mapped or listed in
ignoredSource; an ignored name must still name an existing public property.
Map nested DTOs and collections
Nested traversal is explicit and uses only an exact registered pair. Select a source member, then configure exactly one terminal operation:
new MappingDefinition(Session::class, SessionDto::class, rules: [ 'token' => MapRule::from('token')->nested(ApiAccessTokenDto::class), 'releases' => MapRule::from('releases')->collection( Release::class, ReleaseDto::class, ), ]);
nested() requires the selected source member to be the exact registered
source class (or its nullable form). collection() deliberately takes both
element classes: PHP can verify that a member is array, but cannot recover an
array element type at runtime. The selected source and target parameter must
therefore be array or ?array; iterables, generators, keyed output, PHPDoc
generic inference, and implicit scalar conversion are unsupported.
Collections preserve input order, discard input keys, and produce a
list<ReleaseDto>. A nullable nested member or collection maps null only to
null, never to an empty array. Nested conventional mappings are compiled as a
dependency graph during warmup; direct and indirect cycles are rejected before
traffic. A nested custom mapper is validated as an exact pair during warmup but
is not invoked until mapping executes.
If a collection element has the wrong runtime class, its diagnostic names the target parameter, expected and actual class, and the input key without rendering the element value. Integer keys are shown directly; string keys are represented by a stable SHA-256 prefix and length, so secret or control-character keys do not enter logs.
Use a hand-written mapper
For policies outside safe member selection, construct and register an application-owned mapper instance. No container or service lookup is involved:
use Sirix\ObjectMapper\Contract\CustomObjectMapperInterface; use Sirix\ObjectMapper\Definition\CustomMappingDefinition; final class UserResultMapper implements CustomObjectMapperInterface { public function map(object $source): object { assert($source instanceof UserResult); return new UserDto($source->uuid, $source->getPrimaryEmail()); } } $registry = new MappingRegistry([ new CustomMappingDefinition(UserResult::class, UserDto::class, new UserResultMapper()), ]);
Custom definitions have the same exact-pair registration and final target-type
check as generated mappers. MappingDefinitionInterface is a read and registry
contract, not an executable extension SPI: core dispatch supports only the
built-in conventional, direct-custom, and provider-custom definition types.
Use CustomObjectMapperInterface with CustomMappingDefinition for custom
execution. warmup() deliberately skips custom mappings and returns only the
generated conventional mapping keys, so a custom mapper is never executed as a
warmup side effect.
Resolve an application-owned custom mapper at runtime
When an application custom mapper needs a service, register an opaque, application-configured identifier instead of exposing a container to the core:
use Sirix\ObjectMapper\Contract\CustomObjectMapperInterface; use Sirix\ObjectMapper\Contract\CustomObjectMapperProviderInterface; use Sirix\ObjectMapper\Definition\ProviderCustomMappingDefinition; final class ApplicationMapperProvider implements CustomObjectMapperProviderInterface { public function __construct(private CustomObjectMapperInterface $userResultMapper) {} public function get(string $mapperId): CustomObjectMapperInterface { // Resolve only a closed application allowlist of identifiers. return match ($mapperId) { 'user-result' => $this->userResultMapper, default => throw new \LogicException('Unknown mapper identifier.'), }; } } $provider = new ApplicationMapperProvider(new UserResultMapper(/* dependencies */)); $registry = new MappingRegistry([ new ProviderCustomMappingDefinition(UserResult::class, UserDto::class, 'user-result'), ]); $cache = new MapperCache( new MappingMetadataFactory($transformers, mappingRegistry: $registry), new PhpMapperGenerator(), __DIR__ . '/var/cache/object-mapper', $transformers, mappingRegistry: $registry, customObjectMapperProvider: $provider, ); $mapper = new ObjectMapper($registry, $cache, customObjectMapperProvider: $provider);
Pass the same provider to ObjectMapper and MapperCache: root, nested, and
collection custom mappings then follow identical behavior. The identifier is an
opaque closed configuration value, never a class name or request-controlled
service key. The core neither instantiates it nor accesses a container. Provider
resolution happens once for each actual custom-mapping invocation; a resolved
mapper is not retained in mapping definitions, metadata, or generated files.
The application owns mapper service scope, recursive mapper use, I/O, and policy. Keep authorization, decryption, and redaction explicit in the custom mapper, and never derive mapper identifiers from request data. Provider and mapper failures are intentionally reported only as a failed mapping pair.
Cache warmup
Use a non-public owner-only (0700) cache directory. The deployment user
must warm it, and the runtime user must be the same owner so it can read the
generated owner-only (0600) files. Production keeps generateOnDemand
disabled and explicitly warms the registered mappings before traffic reaches
the release:
use Sirix\ObjectMapper\Contract\WarmableObjectMapperInterface; /** @var WarmableObjectMapperInterface $warmableMapper */ $warmableMapper = $mapper; $warmableMapper->warmup();
ObjectMapperInterface is mapping-only so application-owned implementations
remain compatible. Request WarmableObjectMapperInterface only from deployment
or cache-warmup wiring that requires warmup().
Warmup compiles every conventional pair and its conventional nested
dependencies in deterministic dependency order, and reports failures together.
Cycles and missing nested registrations fail warmup rather than recursing at
runtime. It is safe to run repeatedly. Development may set generateOnDemand: true; this is a local
convenience, not a substitute for CI/deployment warmup. Generated files are
locked, linted, atomically published, checked for safe owner-only permissions,
and ignored by Git. Do not place the cache in a shared or attacker-writable
directory. Deploy the transformer classes and application wiring first, then
warm the cache with the same registry that production will use. A transformer
signature or source-file change intentionally invalidates the generated mapper
cache; warm again after every such deployment. Constant values participate in
the same cache identity and are emitted as fixed literals, so re-warm after a
constant registration changes as well.
Prepared cache for long-running workers
By default, each conventional mapping execution revalidates its metadata and generated-cache key. This is the development-safe mode: changes to mapped source, target, or transformer PHP files are detected by the normal cache-key path in a live process.
For a production worker with a fixed, application-owned mapping registry, opt
in to reuse the prepared conventional mapping for the lifetime of each exact
MappingDefinition object:
$cache = new MapperCache( new MappingMetadataFactory($transformers, mappingRegistry: $registry), new PhpMapperGenerator(), __DIR__ . '/var/cache/object-mapper', $transformers, generateOnDemand: false, mappingRegistry: $registry, reusePreparedMappings: true, ); $mapper = new ObjectMapper($registry, $cache); // Run once while the worker boots, before it accepts requests. $mapper->warmup();
This opt-in avoids repeated reflection, source-file hashing, metadata normalization, and generated-code rendering for a prepared definition. It is a trust boundary: live PHP code edits and registration changes are not detected in an already running worker. Deploy in this order:
publish application code and trusted registrations
-> start or restart every PHP worker
-> construct the mapper with reusePreparedMappings: true
-> warmup() successfully
-> accept traffic
Restart or reload every worker whenever mapped source, target, transformer, or
mapping-registration code changes. Prepared entries are local to one worker;
they are neither shared nor synchronized between workers. Keep
generateOnDemand: false in production and do not defer first-time preparation
until traffic is being served.
The registry must be fixed application configuration. Do not put
MappingDefinition instances derived from request, tenant, or user input in a
shared long-running registry, and do not retain request state in definitions,
transformers, or custom mappers. Distinct dynamic definitions may retain
generated mappers for a worker lifetime. Custom and provider-custom mappings
continue to execute through their own runtime dispatch and are not prepared by
this option.
Worker operations
- FrankenPHP worker mode: construct and warm the mapper during each worker boot, then gracefully restart workers after deployment. Use file watching only for local development, not as production invalidation.
- RoadRunner: warm during worker boot and reload the worker pool after a
deployment (for example,
rr reset). - Swoole/OpenSwoole: publish the release first, then gracefully reload workers so every replacement worker boots and warms before serving requests. This mode is supported only for non-yielding mapping operations. A source getter, transformer, or custom mapper must not yield through coroutine I/O while mapping; the Fiber isolation coverage is for native PHP Fibers, not a Swoole/OpenSwoole coroutine-local context.
Mapping failures retain structured pair/parameter diagnostics. Do not add the mapped source object or its values to application logs.
Benchmarking prepared mappings
Run the included benchmark after dependency installation:
php tools/benchmark.php
It emits JSON with the median of five rounds for throughput, wall-clock time, current-process user/system CPU time, and PHP-memory deltas. CPU time excludes child processes, so do not use the cold-first result as a total deployment CPU measurement: it includes generated-file linting in a child PHP process.
On this project's PHP 8.2 CLI environment (OPcache CLI and JIT disabled), an illustrative run after warmup produced:
| Scenario | Default | Prepared | CPU time per mapping |
|---|---|---|---|
| Simple DTO | 5,064 ops/s | 612,920 ops/s | 0.1966 ms → 0.00162 ms |
| Nested DTO | 1,684 ops/s | 213,770 ops/s | 0.5823 ms → 0.00468 ms |
| Collection of 100 DTOs | 1,534 ops/s | 7,118 ops/s | 0.6509 ms → 0.1404 ms |
The hot-path runs retained no additional PHP allocator memory between rounds. Run the benchmark on target hardware and compare ratios rather than treating these absolute values as a production capacity guarantee.
Upgrading to 0.8.0
Create one MappingRegistry during application wiring and pass that same
instance to both MappingMetadataFactory and MapperCache for structural
rules. Existing transformer wiring remains shared in the same way. Direct
CustomMappingDefinition registrations are unchanged. For provider-backed
definitions, additionally pass the same optional provider to ObjectMapper
and MapperCache, as shown above. warmup() skips every custom mapping,
including provider-backed children: it neither resolves a provider nor creates
or executes a custom mapper.
Release 0.8.0 retains generated-mapper cache format 6; no generated-cache
or cache-identity migration is required. Deploy the updated code and trusted
registrations, then warm the owner-only (0700) cache as the runtime owner
before serving traffic.
Mapping rules and guarantees
- Source and target must be existing concrete classes and each pair is unique.
Every built-in definition rejects a
class_alias()value: registrations must use the exact canonical name returned byReflectionClass::getName(). ConventionalMappingDefinitionpairs must additionally use named concrete classes; direct and provider-backed custom definitions may use anonymous concrete classes. - The target needs a public constructor. Values are passed by named argument.
- A target parameter resolves, in order, from a public non-static property,
public zero-argument
getX(), or boolean-onlyisX()method. - Required source and target declarations must be type-compatible. Untyped
source values, narrowing
mixed, nullability violations, and unsupported access fail before generated code is loaded. - Generated mappers read only validated source members and fixed validated
constant literals; they never use reflection writes, magic access, or
eval(). - Mapping exceptions identify the pair, target parameter, or configured selector needed for diagnosis. They do not include mapped values; do not add source objects containing sensitive data to application logs.
Non-goals
This is not a serializer or a mapper for untrusted HTTP/JSON input. It has no
automatic casts, implicit nested/collection traversal, reverse mapping,
mapping into existing objects, framework/container integration, source-side
attributes, or generic container access. Provider-backed custom mappers use a
narrow, application-owned opaque-ID contract; a framework bridge, allowlist,
and any PSR-11/container integration remain outside this package. iterable, Traversable,
generators, PHPDoc element inference, keyed collection output, and scalar
element conversion are intentionally excluded. Transformations are limited to explicitly
registered, type-checked through() rules; they are not a general expression,
callback, conditional, closure, property path, dynamic method, or
service-resolution mechanism. Use hand-written mappers for policies outside
these trusted mapping boundaries.