PHP code example of krak / marshal

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

    

krak / marshal example snippets




use Krak\Marshal as m;

$users = getUsers(); // get users from an orm or something

$m = m\map(function($user)
{
    return m\merge([
        m\keys(['id', 'first_name', 'last_name']),
        function($user) {
            return [
                'like_count' => (int) $user->like_count,
                'biography' => substr($user->biography, 0, 64),
                'created_at_ts' => $user->created_at->getTimestamp(),
            ];
        }
    ]);
});

$marshaled = $m($users);

/*
[
    [
        'id' => ...,
        'first_name' => ...,
        'last_name' => ...,
        'biography' => ...,
        'created_at_ts' => ...,
    ],
    ...
]
*/



interface Access {
    public function get($data, $key, $default = null);
    public function has($data, $key);
}



$access = new Krak\Marshal\ArrayKeyAccess();
$data = ['a' => 1];
$access->has($data, 'a'); // true
$access->has($data, 'b'); // false
$access->get($data, 'a'); // 1
$access->get($data, 'b', 0); // 0



interface Hydrator {
    public function __invoke($class, $data);
}



class MyClass {
    public $a;
    public $b;
}

$hydrate = publicPropertyHydrator();
$obj = $hydrate(new MyClass(), [
    'a' => 1,
    'b' => 2,
]);

// $obj now is hydrated with those values



class MyClass {
    public $a;
}

$marshal = Krak\Marshal\hydrate(MyClass::class);
$obj = $marshal(['a' => 1]);
assert($obj instanceof MyClass);



$m = pipe([camelizeKeys(), keys(['id', 'firstName'])]);
$m(['id' => 1, 'first_name' => 2]);



$xml = <<<XML
<?xml version="1.0"