PHP code example of scriptfusion / mapper

1. Go to this page and download the library: Download scriptfusion/mapper library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

scriptfusion / mapper example snippets


$mappedData = (new Mapper)->map($data, new MyMapping);

$fooData = ['foo' => 123];

class FooToBarMapping extends Mapping
{
    protected function createMapping()
    {
        return ['bar' => new Copy('foo')];
    }
}

$barData = (new Mapper)->map($fooData, new FooToBarMapping);

protected function createMapping()
{
    return [
       'foo' => new FooMapping,
       'bar' => new BarMapping,
    ]
}

protected function createMapping()
{
    return new Merge(new FooMapping, new BarMapping);
}

$fooBookAddress = [
    'address' => [
        'name' => 'Mr A Smith',
        'address_line1' => '3 High Street',
        'address_line2' => 'Hedge End',
        'city' => 'SOUTHAMPTON',
        'post_code' => 'SO31 4NG',
    ],
    'country' => 'UK',
];

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'),
        ];
    }
}

$address = (new Mapper)->map($fooBookAddress, new FooBookAddressToAddresesMapping);

// Output.
[  
    'line1' => '3 High Street',
    'line2' => 'Hedge End',
    'city' => 'SOUTHAMPTON',
    'postcode' => 'SO31 4NG',
    'country' => 'UK',
]

$barBucketAddress = [
    'Addresses' => [
        [
            'Jeremy Martinson, Jr.',
            '455 Larkspur Dr.',
            'Baviera, CA 92908',
        ],
    ],
];

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];
    }
}

$address = (new Mapper)->map($barBucketAddress, new BarBucketAddressToAddresesMapping);

// Output.
[
    'line1' => '455 Larkspur Dr.',
    'city' => 'Baviera',
    'postcode' => '92908',
    'country' => 'US',
],

Copy(Strategy|Mapping|array|mixed $path, Strategy|Mapping|array|mixed $data)

$data = [
    'foo' => [
        'bar' => 123,
    ],
];

(new Mapper)->map($data, new Copy('foo'));

(new Mapper)->map($data, new Copy('foo->bar'));
// or
(new Mapper)->map($data, new Copy(['foo', 'bar']));

(new Mapper)->map(
    ['foo' => 'bar'],
    new Copy('foo', ['foo' => 'baz'])
);

(new Mapper)->map(
    [
        'foo' => 'bar',
        'bar' => 'baz',
        'baz' => 'qux',
    ],
    new Copy(new Copy(new Copy('foo')))
);

CopyContext(Strategy|Mapping|array|mixed $path)

$data = ['foo' => 123];
$context = ['foo' => 456];

(new Mapper)->map($data, new CopyContext('foo'), $context);

CopyKey()

(new Mapper)->map(
    [
        'foo' => [
            'bar' => 'baz',
        ],
    ],
    new Collection(
        new Copy('foo'),
        new CopyKey
    )
)

Callback(callable $callback)

(new Mapper)->map(
    range(1, 5),
    new Callback(
        function ($data) {
            $total = 0;

            foreach ($data as $number) {
                $total += $number;
            }

            return $total;
        }
    )
);

Collection(Strategy|Mapping|array|mixed $collection, Strategy|Mapping|array|mixed $transformation)

(new Mapper)->map(
    ['foo' => range(1, 5)],
    new Collection(
        new Copy('foo'),
        new Callback(
            function ($data, $context) {
                return $context * 2;
            }
        )
    )
);

Context(Strategy|Mapping|array|mixed $expression, Strategy|Mapping|array|mixed $context)

(new Mapper)->map(
    ['foo' => 123],
    new Context(
        new CopyContext('foo'),
        ['foo' => 456]
    ),
    ['foo' => 789]
);

Either(Strategy $strategy, Strategy|Mapping|array|mixed $expression)

(new Mapper)->map(
    ['bar' => 'bar'],
    new Either(new Copy('foo'), new Copy('bar'))
);

Filter(Strategy|Mapping|array|mixed $expression, callable $callback = null)

(new Mapper)->map(
    ['foo' => range(1, 10)],
    new Filter(
        new Copy('foo'),
        function ($value) {
            return $value % 2;
        }
    )
);

Flatten(Strategy|Mapping|array|mixed $expression)

$data = [
    'foo' => [
        range(1, 3),
        'bar' => [range(3, 5)],
    ],
];

(new Mapper)->map($data, new Flatten(new Copy('foo')));

(new Mapper)->map($data, (new Flatten(new Copy('foo')))->ignoreKeys());

IfElse(callable $condition, Strategy|Mapping|array|mixed $if, Strategy|Mapping|array|mixed $else = null)

(new Mapper)->map(
    ['foo' => 'foo'],
    new IfElse(
        function ($data) {
            return $data['foo'] !== 'bar';
        },
        true,
        false
    )
);

IfExists(Strategy $condition, Strategy|Mapping|array|mixed $if, Strategy|Mapping|array|mixed $else = null)

$data = ['foo' => 'foo'];

(new Mapper)->map($data, new IfExists(new Copy('foo'), true, false));

(new Mapper)->map($data, new IfExists(new Copy('bar'), true, false));

Join(string $glue, array ...$expressions)

(new Mapper)->map(
    ['foo' => 'foo'],
    new Join('-', new Copy('foo'), 'bar')
);

(new Mapper)->map(
    ['foo' => ['bar', 'baz']],
    new Join('-', new Copy('foo'))
);

Merge(Strategy|Mapping|array|mixed $first, Strategy|Mapping|array|mixed $second)

(new Mapper)->map(
    [
        'foo' => range(1, 3),
        'bar' => range(3, 5),
    ],
    new Merge(new Copy('foo'), new Copy('bar'))
);

Regex(Strategy|Mapping|array|mixed $expression, string $regex, int $capturingGroup = 0)

(new Mapper)->map(
    ['foo bar baz'],
    new Replace(
        new Copy(0),
        '[\h(.+)\h]',
        1,
    )
)

Replace(Strategy|Mapping|array|mixed $expression, string|Expression|array $searches, string|string[]|null $replacements)

(new Mapper)->map(
    ['Hello World'],
    new Replace(
        new Copy(0),
        ['Hello', new Expression('[\h*world$]i')],
        ['こんにちは', '世界']
    )
)

TakeFirst(Strategy|Mapping|array|mixed $collection, int $depth = 1)

(new Mapper)->map(
    [
        'foo' => [
            'bar' => [
                'baz' => 123,
                'quz' => 456,
            ],
        ],
    ],
    new TakeFirst(new Copy('foo'), 2)
);

ToList(Strategy|Mapping|array|mixed $expression)

(new Mapper)->map(['foo' => 'bar'], new ToList(new Copy('foo')));

TryCatch(Strategy $strategy, callable $handler, Strategy|Mapping|array|mixed $expression)

(new Mapper)->map(
    ['foo' => 'bar'],
    new TryCatch(
        new Callback(
            function () {
                throw new \DomainException;
            }
        ),
        function (\Exception $exception, array $data) {
            if (!$exception instanceof \DomainException) {
                throw $exception;
            }
        },
        new Copy('foo')
    )
);

Type(DataType $type, Strategy $strategy)

(new Mapper)->map(['foo' => 123], new Type(DataType::String, new Copy('foo')));

Unique(Strategy|Mapping|array|mixed $collection)

(new Mapper)->map(
    ['foo' => array_merge(range(1, 3), range(3, 5))],
    new Unique(new Copy('foo'))
);

Debug(Strategy|Mapping|array|mixed $expression)