Mapper

Mapper transforms arrays from one format to another using an object composition DSL. An application often receives data from a foreign source structured differently than it wants. We can use Mapper to transform foreign data into a more suitable format for our application using a Mapping as shown in the following example.
$mappedData = (new Mapper)->map($data, new MyMapping);
This supposes we already created a mapping, MyMapping, to convert $data into $mappedData.
Contents
- Mappings
- Strategies
- Practical example
- Strategy reference
- Fetchers
- Copy
- CopyContext
- CopyKey
- Augmenters
- Callback
- Collection
- Context
- Either
- Filter
- Flatten
- IfElse
- IfExists
- Join
- Merge
- Regex
- Replace
- TakeFirst
- ToList
- TryCatch
- Type
- Unique
- Others
- Debug
- Requirements
- Limitations
- Testing
Mappings
Mappings are data transformation descriptions that describe how to convert data from one format to another. Mappings are an object wrapper for an array, which describes the output format, with expressions that can fetch and augment input data. To write a mapping we must know the input data format so we can write an array that represents the desired output format and decorate it with expressions to transform the input data.
Example
In the following simple but contrived example we use a mapping to effectively rename the input array's key from foo to bar.
$fooData = ['foo' => 123];
class FooToBarMapping extends Mapping
{
protected function createMapping()
{
return ['bar' => new Copy('foo')];
}
}
$barData = (new Mapper)->map($fooData, new FooToBarMapping);
['bar' => 123]
In this example we declare a mapping, FooToBarMapping, and pass it to the Mapper::map method to transform $fooData into $barData. As mentioned, this is just a contrived example to demonstrate how Mapper works; one may like to see a more practical example.
This mapping introduces the Copy strategy that copies a value from the input data to the output. Strategies are just one type of expression we can specify as mapping values.
Expressions
An expression is a pseudo-type representing the list of valid mapping value types. The keys of a mapping are never modified by Mapper but its values may change depending on the expression type. Following is the list of valid expression types; any other type causes InvalidExpressionException to be thrown.
Strategy
Mapping
- Mapping fragment
- Scalar
null
Strategies are invoked and substituted as described in the following section. Mappings may contain any number of additional embedded mappings or mapping fragments—a mapping fragment is just a mapping described by an array instead of a Mapping object. Scalar values (integer, float, string and boolean) and null have no special meaning and are presented verbatim in the output.
Writing a mapping
To write a mapping create a new class that extends Mapping and implement its abstract method, createMapping(), that returns a strategy or an array describing the output format with any combination of expressions.
For prototyping purposes we can avoid writing a new mapping class and instead create an AnonymousMapping, passing the mapping definition to its constructor, which can be quicker than writing a new class. However, the recommended way to write mappings is to write new classes so mappings have meaningful names to identify them.
It is recommended to name mapping classes XToYMapping where X is the name of the input format and Y is the name of the output format.
Strategy-based mappings
Strategy-based mappings are created by specifying a strategy at the top level. Usually mappings are array-based, and although such mappings may contain other expressions, including strategies, at the top level they are an array.
Some problems can only be solved with strategy-based mappings. For example, suppose we want to create a mapping that combines two other mappings at the top level. With array-based mappings the best we can do is something like the following.
protected function createMapping()
{
return [
'foo' => new FooMapping,
'bar' => new BarMapping,
]
}
This composes FooMapping and BarMapping in our mapping but each mapping will be mapped under new foo and bar keys respectively. What we really want is to combine the keys of each mapping together at the top level of our mapping but there is no way to express a solution to this problem with array-based mappings. If we use the Merge strategy as the basis of our mapping we can solve this problem.
protected function createMapping()
{
return new Merge(new FooMapping, new BarMapping);
}
Strategies
Strategies are invokable classes that are invoked by Mapper and substituted for their return values. Strategies can be broadly broken down into two categories: fetchers and augmenters. Fetch strategies retrieve data while augmenters change data provided by other strategies.
Strategies are basic building blocks from which complex data manipulation chains can be constructed to meet the bespoke requirements of an application. The composition of strategies forms a powerful object composition DSL that allows us to express how to retrieve and augment data to mould it into the desired format.
For a complete list of strategies please see the strategy reference.
Writing strategies
Strategies must implement the Strategy interface but it is common to extend Delegate or Decorator because we usually write augmenters which expect another strategy injected into them to provide data. Delegate and Decorator provide the delegate() method, which allows a strategy to evaluate an expression using Mapper, and is usually needed to evaluate the injected strategy. Delegate can delegate any expression to Mapper whereas Decorator only accepts Strategy objects.
It is recommended to name custom strategies with a Strategy suffix to help distinguish them from stock strategies.
Practical example
Suppose we receive two different postal address formats from two different third-party providers. The first provider, FooBook, provides a single UK addresses. The second provider, BarBucket, provides a collection of US addresses. We are tasked with converting both types to the same uniform address format for our application using mappings.
The address format for our application must be a flat array with the following fields.
- line1
- line2 (if applicable)
- city
- postcode
- country
FooBook address mapping
A sample of the data we receive from FooBook is shown below.
$fooBookAddress = [
'address' => [
'name' => 'Mr A Smith',
'address_line1' => '3 High Street',
'address_line2' => 'Hedge End',
'city' => 'SOUTHAMPTON',
'post_code' => 'SO31 4NG',
],
'country' => 'UK',
];
Before continuing, consider attempting to create the mapping on your own, consulting the reference if unsure which strategies to use. The following code shows how we can create a mapping to convert this address format to our application's format.
class FooBookAddressToAddresesMapping extends Mapping
{
protected function createMapping()
{
return [
'line1' => new Copy('address->address_line1'),
'line2' => new Copy('address->address_line2'),
'city' => new Copy('address->city'),
'postcode' => new Copy('address->post_code'),
'country' => new Copy('country'),
];
}
}
Since the input data already has the values we want we only need to effectively rename the fields using Copy strategies. We do not need the name field so it is left unmapped.
The result of mapping the input data is shown below.
$address = (new Mapper)->map($fooBookAddress, new FooBookAddressToAddresesMapping);
// Output.
[
'line1' => '3 High Street',
'line2' => 'Hedge End',
'city' => 'SOUTHAMPTON',
'postcode' => 'SO31 4NG',
'country' => 'UK',
]
BarBucket address mapping
A sample of the data we receive from BarBucket is show below.
$barBucketAddress = [
'Addresses' => [
[
'Jeremy Martinson, Jr.',
'455 Larkspur Dr.',
'Baviera, CA 92908',
],
],
];
This format is a lot less similar to our application's format. In particular, BarBucket's format supports multiple addresses but we're only interested in mapping one so we'll assume the first will suffice and discard any others. Their format also omits the country but we know BarBucket only supplies US addresses so we can assume the country is always "US". Once again, consider attempting to create the mapping on your own before observing the solution below.
class BarBucketAddressToAddresesMapping extends Mapping
{
protected function createMapping()
{
return [
'line1' => new Copy('Addresses->0->1'),
'city' => new Callback(fn (array $data) => $this->extractCity($data['Addresses'][0][2])),
'postcode' => new Regex(new Copy('Addresses->0->2'), '[.*\b(\d{5})]', 1),
'country' => 'US',
];
}
private function extractCity($line)
{
return explode(',', $line, 2)[0];
}
}
Line1 can be copied straight from the input data and country