Download the PHP package elaitech/data-mapper without Composer
On this page you can find all versions of the php package elaitech/data-mapper. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download elaitech/data-mapper
More information about elaitech/data-mapper
Files in elaitech/data-mapper
Package data-mapper
Short Description DataMapper - A reusable, framework-agnostic data mapping and transformation component for Laravel.
License MIT
Informations about the package data-mapper
๐ฆ DataMapper
A reusable data mapping and transformation library for Laravel 12. Maps source fields to target fields with per-rule value transformers, dot-notation and wildcard field extraction, value mapping lookups, and full support for both associative and indexed (header-based) data rows.
Namespace:
Medox\DataMapper
Requires: PHP 8.4+ ยท Laravel 12 ยทspatie/laravel-data^4.19
๐ Table of Contents
- Installation
- Architecture
- Quick Start
- Core Components
- Built-in Transformers
- Transformer Groups
- Column Matching
- Field Extraction
- Value Mapping
- Creating Custom Transformers
- DTOs
- Contracts
- Testing
- License
๐ Installation
From GitHub
As a local Composer package
In your root composer.json, add the package as a path repository:
Then install:
The DataMapperServiceProvider is auto-discovered by Laravel. It registers:
DataMapperInterfaceโDataMapperService(binding)ValueTransformerโ singleton with the 10 built-in transformers in thecoregroup, plus anything declared inconfig/data-mapper.phpNormalizerInterfaceโ singleton, fromdata-mapper.normalizerColumnMatcherInterfaceโ singleton, fromdata-mapper.column_matcherValueMatcherInterfaceโ singleton, fromdata-mapper.value_matcherFieldExtractorโ singleton, wired to that matcher
To register your own transformers, publish the config:
๐ Architecture
โก Quick Start
๐งฉ Core Components
DataMapperService
The main service class. Implements DataMapperInterface.
Behaviour:
- Automatically detects whether rows are associative (
['name' => 'John']) or indexed (['John', '[email protected]']) - For indexed rows, uses the
headersarray to resolve field positions - Wraps each row in a try/catch โ failed rows are captured as errors, not exceptions
- Returns
DataMappingResultDatawith mapped data and any per-row errors
FieldExtractor
Extracts values from data using:
| Pattern | Example | Description |
|---|---|---|
| Direct access | name |
Top-level field |
| Dot notation | address.city |
Nested field traversal |
| Wildcard | items.*.name |
Extract from all array elements |
| Numbered | image* |
Collect a numbered set of columns into one ordered list |
ValueTransformer
The transformer registry and execution engine. Holds the registered transformers and applies the one a rule names.
See Transformer Groups for narrowing what a given screen offers.
Transformation flow:
- Check if value is empty โ return
defaultValue(unless it's an array transformer) - Apply value mapping if configured (lookup table)
- Apply transformer (type conversion, formatting)
- If result is empty string and
defaultValueis set โ returndefaultValue
๐ง Built-in Transformers
A rule names one transformer. There is no chaining: to apply two steps, map through an intermediate target or register a transformer that does both.
| Name | Label | Description | Requires Format |
|---|---|---|---|
none |
None | Pass-through, no transformation | โ |
trim |
Trim | Remove leading/trailing whitespace | โ |
upper |
Uppercase | Convert to UPPERCASE | โ |
lower |
Lowercase | Convert to lowercase | โ |
int |
Integer | Plain (int) cast โ see the note below |
โ |
float |
Float | Cast to float, stripping non-numeric characters |
โ |
bool |
Boolean | Cast to bool (handles "true", "1", "yes", etc.) |
โ |
date |
Date | Parse to ?DateTimeImmutable; unparseable yields null, never throws |
โ (date format) |
array_first |
Array First | Extract first element from array | โ |
array_join |
Array Join | Join array elements with separator | โ (separator) |
floatstrips non-numeric characters and ignores$format. It handles'$31,500'โ31500.0, but concatenates every digit in'$31,500 (was $35,000)'โ3150035000.0. That is a known bug; do not rely on it for free-text numeric fields.
intis a plain cast, on purpose. PHP takes the leading numeric run and discards the rest, so'41,000'is41and'$31,500'is0. Working out what number the source meant would mean guessing what a comma is for โ it groups thousands in one locale and marks a decimal in another โ so this transformer does not try. A source that writes numbers with separators or symbols wants a format-aware transformer, where the convention is stated rather than assumed. (floatcurrently strips non-numeric characters, which handles'$31,500'but concatenates every digit in'$31,500 (was $35,000)'โ a known bug, not a feature to rely on.)
๐ฅ Transformer Groups
The ten built-in transformers are type-level operations โ trim, int, date โ that mean
the same thing everywhere. Anything carrying business meaning belongs to your application,
not to this package. Groups are how you keep it there: you name a group, register your own
transformers into it, and ask for the groups a given screen should offer.
The package never interprets a group name. import, export, syndication, crm โ it only
answers which transformers are in one.
Declaring groups in config
Publish the config and list your classes under the group they belong to:
Each class is resolved through the container, so it may declare its own dependencies. A class
that does not implement TransformerInterface throws at boot rather than silently doing
nothing halfway through a feed.
Registering groups at runtime
Letting a transformer choose its own group
Implement GroupedTransformerInterface and the registration site no longer has to repeat the
group name:
A group passed explicitly to registerTransformer() โ or listed in config โ always wins over
the one the class declares.
Querying groups
Groups describe what a UI should offer, not what a pipeline may run.
ValueTransformer::transform()resolves a rule's transformer by name across every group, so a stored mapping keeps working even if a screen would no longer offer that transformer.
๐ค Column Matching
A mapping rule names a column โ dealer id, stocknumber. The source exports whatever it
exports โ Dealer ID, StockNumber. With a byte-exact lookup those are different columns
and the value comes back null, with no error, because a rule that is not required is
allowed to find nothing. A configuration can name twenty columns, match none of them, and
map blank rows while reporting success.
RelaxedColumnMatcher is the default. An exact key always wins; only when none exists is
the name compared with letter case, surrounding whitespace and a byte-order mark folded
away:
It works the same for positional headers (headers: ['VIN', 'Dealer ID'] with list-shaped
rows) and for every segment of a nested path (vehicle.engine.cylinders finds
Vehicle.Engine.Cylinders).
Why this is safe to have on: the relaxed pass runs only when no exact key exists, so it
can never change a lookup that already found a value โ it can only rescue one that found
nothing. A source carrying both price and Price keeps them apart for whichever one was
configured.
What it will not do: guess across separators. stock_number and Stock Number stay
different columns, because that would start mapping fields nobody asked for.
Choosing a policy
The normalizer is one decision, shared
What counts as formatting is configured once and used by both column matching and value mapping, so the two can never drift apart:
To move the line, implement NormalizerInterface:
Results are cached, so an implementation must be a pure function of its argument. If only
column names need a rule of their own, RelaxedColumnMatcher::normalize() is still
protected and overridable. Anything implementing ColumnMatcherInterface is also
accepted, if folding a name is not how your sources work at all.
Resolve
DataMapperServicefrom the container and the configured matcher is used for both keyed rows and positional headers. Construct it by hand and you must pass the same matcher toFieldExtractorand toDataMapperServiceyourself.
๐บ Field Extraction
Dot Notation
Access nested fields in associative arrays:
Wildcard Notation
Extract values from arrays of objects:
Numbered Notation
Collect the columns a source spread across a numbered set of them โ a gallery shipped one column per photo โ into one list under a single target:
* stands for digits, and may sit anywhere in the name: Photo* reads
Photo1 โฆ Photo25, Image_*_URL reads Image_1_URL โฆ Image_5_URL, and a dotted
prefix still addresses a nested object (photos.image*).
It matches digits rather than any suffix so that it is usable on a real feed: a
plain prefix match on image would also collect imagecaption, imagecount and
imagemodifieddate, none of them a photo.
The number orders the list, not the order the row carries its keys in โ the two
agree until a feed reaches image10, which arrives between image1 and image2.
Columns present but empty are dropped, so three photos in a nine-column feed yield
three values. Case is forgiven; a row carrying none of the columns extracts null,
which is what makes required on such a rule mean "at least one was present".
Indexed (Header-Based) Rows
For data without keys (e.g., CSV rows), provide headers:
๐ Value Mapping
Map specific values using a lookup table. Useful for code-to-label conversions:
Value mapping is applied before the transformer, so you can combine both:
How loosely a value matches
A mapping is a statement about what a source's value means, and " Used" does not mean
something different from "Used". With a byte-exact lookup it did: a hand-written
Used โ used silently missed every row a provider happened to send as USED, the value
reached the target un-normalised, and the field then failed its cast for the whole file.
RelaxedValueMatcher is the default. An exact key always wins; only when none exists is the
value compared through the normalizer:
Colliding keys are dropped, not shadowed. If you write both Used โ second-hand and
USED โ pre-owned, you plainly meant them apart โ you typed both, in one table. Each still
answers for its own exact spelling, but a third spelling matching neither gets no answer
rather than an arbitrary winner. This is the deliberate difference from column matching,
where colliding keys are an accident of the data and the first one wins.
Only strings and integers are mapped. null means absent, not "matches the empty
key"; an array is a multi-value extraction and is mapped element by element; and folding a
float or bool into a key would invent a numeric equivalence that belongs to a transformer,
not to a lookup.
๐ Creating Custom Transformers
Implement the TransformerInterface:
Register it:
Or register in a service provider for global availability:
A transformer that carries business meaning should go in a group of its own rather than in
core โ see Transformer Groups. The declarative route is
config/data-mapper.php:
๐ DTOs
MappingConfigurationData
Input to the mapper:
| Property | Type | Description |
|---|---|---|
data |
array |
Array of rows to map |
mappingRules |
DataCollection<MappingRuleData> |
Mapping rules to apply |
headers |
?array |
Column headers for indexed rows |
MappingRuleData
A single field mapping rule:
| Property | Type | Default | Description |
|---|---|---|---|
sourceField |
string |
โ | Source field name (supports dot/wildcard/numbered notation) |
targetField |
string |
โ | Target field name in output |
transformation |
?string |
null |
Transformer name to apply; null means none |
isRequired |
bool |
false |
Throw if source field is missing |
defaultValue |
mixed |
null |
Fallback for empty values |
format |
?string |
null |
Format parameter for transformers (e.g., date format) |
valueMapping |
?array |
null |
Value lookup table ([['from' => ..., 'to' => ...]]) |
A rule naming no transformation carries
null, not'none'. Both mean "leave the value alone", andnullis the shape a form already produces โ an empty string thatConvertEmptyStringsToNullturns into null before it is stored.transform()skips the transformer lookup on null. An unregistered name behaves the same way.
DataMappingResultData
Output from the mapper:
| Property | Type | Description |
|---|---|---|
mappedData |
array |
Successfully mapped rows |
errors |
array |
Per-row error messages |
๐ Contracts
DataMapperInterface
TransformerInterface
ColumnMatcherInterface
ValueMatcherInterface
NormalizerInterface
GroupedTransformerInterface
Optional. Extends TransformerInterface with a single method so a transformer can name the
groups it belongs to:
An explicit group at the registration site, or in config/data-mapper.php, overrides it.
๐งช Testing
๐ฆ Dependencies
| Package | Version | Purpose |
|---|---|---|
illuminate/support |
^12.0 | Laravel framework support |
spatie/laravel-data |
^4.19 | Typed DTOs with auto-mapping |
๐ License
MIT
All versions of data-mapper with dependencies
illuminate/support Version ^12.0|^13.0
spatie/laravel-data Version ^4.19