xp-forge/marshalling

v2.2.0 2024-03-24 12:15 UTC

This package is auto-updated.

Last update: 2024-04-24 12:27:45 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

Marshalling converts objects to maps and vice versa.

Example

All primitives, arrays and maps thereof are yielded as-is:

use util\data\Marshalling;

$m= new Marshalling();
$m->marshal('Test');            // "Test"
$m->marshal([1, 2, 3]);         // [1, 2, 3]
$m->marshal(['admin' => true]); // ["admin" => true]

Value objects are marshalled using field => getter lookups; supporting both method named for field and getField conventions.

use util\data\Marshalling;

class Person {
  private $name, $age;

  public function __construct(string $name, int $age) {
    $this->name= $name;
    $this->age= $age;
  }

  public function name(): string { return $this->name; }
  public function age(): int { return $this->age; }
}

$m= new Marshalling();
$m->marshal(new Person('...', 42)); // ["name" => "...", "age" => 42]

When unmarshalling from maps, pass the type as second parameter. Objects are created without invoking the constructor, and by either setting the fields directly or by using the setField convention.

use util\data\Marshalling;

$m= new Marshalling();
$person= $m->unmarshal(['name' => '...', 'age' => 42], Person::class);

Types from the "util" package are handled:

use util\data\Marshalling;
use util\{Date, Bytes, Money};

$m= new Marshalling();
$m->marshal(Date::now());                   // "2018-08-29T10:40:49+0200" (ISO 8601)
$m->marshal(new Bytes("\x50\x4b\x03\x04")); // "UEsDBA==" (base64)
$m->marshal(new Money(12.99, $currency));   // ["amount" => 12.99, "currency" => "EUR"]

See also: