PHP code example of dazet / data-map

1. Go to this page and download the library: Download dazet/data-map 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/ */

    

dazet / data-map example snippets


use DataMap\Getter\GetInteger;
use DataMap\Mapper;
use DataMap\Input\Input;

// Input structure is:
$input = [
    'name' => 'John',
    'surname' => 'Doe',
    'date_birth' => '1970-01-01',
    'address' => [
        'street' => 'Foo Street',
        'city' => [
            'name' => 'Bar Town',
            'country' => 'Neverland',
        ],
    ],
    'age' => '47',
];

// Required output structore is:
$output = [
    'firstName' => 'John',
    'fullName' => 'John Doe',
    'street' => 'Foo Street',
    'city' => 'Bar Town',
    'age' => 47,
    'birth' => new \DateTimeImmutable('1970-01-01'),
];

// Then mapping definition is:
$mapper = new Mapper([
    'firstName' => 'name',                          // simply get `name` from input and assign to `firstName` property
    'fullName' => function (Input $input): string {
        return $input->get('name') . ' ' . $input->get('surname');
    },                                              // use Closure as Getter function
    'street' => 'address.street',                   // get values from nested structures
    'city' => 'address.city.name',
    'age' => new GetInteger('age'),                 // use one of predefined getters
    'birth' => new GetDate('date_birth'),           // get date as `\DateTimeImmutable` object
]);

// Map $input to $output:
$output = $mapper->map($input);

// Map collection of entries:
$outputCollection = array_map($mapper, $inputCollection);

// Extend mapper definition:
$newMapper = $mapper->withAddedMap(['country' => 'address.city.country']);

use DataMap\Input\Input;

interface Getter
{
    /**
     * @return mixed
     */
    public function __invoke(Input $input);
}

$mapper = new Mapper([
    'name' => new GetRaw('first_name'),
    // same as:  
    'name' => 'first_name',  
]);

$mapper = new Mapper([
    'name' => new GetString('username', 'anonymous'),
]);

$mapper = new Mapper([
    'age' => new GetInteger('user.age', null),
]);

$mapper = new Mapper([
    'fullname' => new GetJoinedStrings(' ', 'user.name', 'user.surname'),
]);

$characterMapper = new Mapper([
    'fullname' => new GetJoinedStrings(' ', 'name', 'surname'),
] );

$movieMapper = new Mapper([
    'movie' => 'name',
    'characters' => new GetMappedCollection('characters', $characterMapper),
]);

$mapper->map([
    'name' => 'Lucky Luke',
    'characters' => [
        ['name' => 'Lucky', 'surname' => 'Luke'],
        ['name' => 'Joe', 'surname' => 'Dalton'],
        ['name' => 'William', 'surname' => 'Dalton'],
        ['name' => 'Jack', 'surname' => 'Dalton'],
        ['name' => 'Averell', 'surname' => 'Dalton'],
    ],
]);

// result:
[
   'movie' => 'Lucky Luke',
   'characters' => [
       ['fullname' => 'Lucky Luke'],
       ['fullname' => 'Joe Dalton'],
       ['fullname' => 'William Dalton'],
       ['fullname' => 'Jack Dalton'],
       ['fullname' => 'Averell Dalton'],
   ],
];

$mapper = new Mapper([
    'agree' => new GetTranslated('agree', ['yes' => true, 'no' => false], false), 
]);

$mapper->map(['agree' => 'yes']) === ['agree' => true];
$mapper->map(['agree' => 'no']) === ['agree' => false];
$mapper->map(['agree' => 'maybe']) === ['agree' => false];

$mapper = new Mapper([
    'text' => GetFiltered::from('html')->string()->stripTags()->trim()->ifNull('[empty]'),
    'time' => GetFiltered::from('datetime')->dateFormat('H:i:s'),
    'date' => GetFiltered::from('time_string')->date(),
    'amount' => GetFiltered::from('amount_string')->float()->round(2),
    'amount_int' => GetFiltered::from('amount_string')->round()->int()->ifNull(0),
]);

$greeting = function (string $name): string {
    return "Hello {$name}!";
};

$mapper = new Mapper([
    'greet' => GetFiltered::from('name')->string()->with($greeting),
]);

$mapper->map(['name' => 'John']); // result: ['greet' => 'Hello John!']

$    if (!is_int($value)) {
        throw new InvalidArgumentException('I  GetFiltered::from('number')->int()->withNullable($d_int' => 1]

$array = ['one' => 1];
$input = new ArrayInput($array);

$input->get('key'); // is translated to: $array['key'] ?? null
$input->get('one'); // 1
$input->get('two'); // null
$input->get('two', 'default'); // 'default'

$input->has('one'); // true
$input->has('two'); // false

class Example
{
    public $one = 1;
    private $two = 2;
    private $three = 3;
    
    public function two(): int
    {
        return $this->two;
    }
    
    public function getThree(): int
    {
        return $this->three;
    }
}

$object = new Example();
$input = new ObjectInput($object);

$input->get('one'); // 1 (public property $object->one)
$input->get('two'); // 2 (getter $object->())
$input->get('three'); // 3 (getter $object->getThree())
$input->get('four'); // null (no property, no getter)
$input->get('four', 'default'); // 'default'

$input->has('one'); // true
$input->has('four'); // false

class Example
{
    public $one = ['nested' => 'nested one'];
    
    public function two(): object
    {
        return (object)['nested' => 'nested two'];
    }
};

$innerInput = new ObjectInput(new Example());
$input = new RecursiveInput($innerInput, MixedWrapper::default());

$input->get('one'); // ['nested' => 'nested one']
$input->get('one.nested'); // 'nested one'
$input->get('one.other'); // null
$input->get('two.nested'); // 'nested two'

$input->has('one'); // true
$input->has('one.nested'); // true
$input->has('one.other'); // false

$innerInput = new ArrayInput([
    'amount' => 123,
    'description' => '  string  ',
    'price' => 123.1234,
]);

$input = new FilteredInput($innerInput, InputFilterParser::default());

$input->get('amount | string'); // '123'
$input->get('description | trim | upper'); // 'STRING'
$input->get('description | integer'); // null
$input->get('price | round'); // 123.0
$input->get('description | round'); // null
$input->get('price | round 2'); // 123.12
$input->get('price | ceil | integer'); // 124

$mapper = new Mapper($map);
// same as:
$mapper = new Mapper($map, new ArrayFormatter());

// by class constructor:
$mapper = new Mapper($map, new ObjectConstructor(SomeClass::class));

// by static method:
$mapper = new Mapper($map, new ObjectConstructor(SomeClass::class, 'method'));

// hydrate instance clone
$mapper = new Mapper($map, new ObjectHydrator(new SomeClass()));

// new instance from class name
$mapper = new Mapper($map, new ObjectHydrator(SomeClass::class));

$mapper = new Mapper($getterMap);

// which is equivalent of:
$mapper = new Mapper(
    $getterMap, 
    ArrayFormatter::default(), 
    FilteredWrapper::default()
);

interface Attributes
{
    public function getAttribute($key, $default = null);
}

class AttributesInput implements Input
{
    /** @var Attribiutes */
    private $attributes;
  
    public function get(string $key, $default = null)
    {
        return $this->attributes->getAttribute($key, $default);
    }
    // ...    
}

class AttributesWrapper implements Wrapper
{
    public function supportedTypes(): array
    {
        return [Attributes::class]
    }
  
    public function wrap($data): Input
    {
        return new AttributesInput($data);
    }
}

$mapper = new Mapper(
    $getterMap, 
    ArrayFormatter::default(), 
    FilteredWrapper::default()->withWrappers(new AttributesWrapper())
);

$mapper = new Mapper(
    $getterMap, 
    ArrayFormatter::default(), 
    MixedWrapper::default()
);

$mapper = new Mapper(
    [
        'slug' => 'title | my_replace "/[\PL]+/u" "-" | trim "-"'
    ], 
    ArrayFormatter::default(), 
    FilteredWrapper::default()->withFilters([
        'my_replace' => new Filter('preg_replace', ['//', '', '$$'])
    ])
);

class Person
{
    /** @var string */
    private $name;

    /** @var string */
    private $surname;

    public function __construct(string $name, string $surname)
    {
        $this->name = $name;
        $this->surname = $surname;
    }
    // ...
}

class PersonFormatter implements Formatter
{
    public function format(array $output): Person
    {
        return new Person($output['name'], $output['surname']);
    }
}

class JsonFormatter implements Formatter
{
    public function format(array $output): string
    {
        return json_encode($output);
    }
}

$map = [
    'name' => 'person.name | string',
    'surname' => 'person.surname | string',
];

$toPerson = new Mapper($map, new PersonFormatter());
$toPerson->map(['person' => ['name' => 'John', 'surname' => 'Doe']]); 
// result: new Person('John', 'Doe');

$toJson = new Mapper($map, new JsonFormatter());
$toJson->map(['person' => ['name' => 'John', 'surname' => 'Doe']]); 
// result: {"name":"John","surname":"Doe"};