Skip to content

Add mapping() and resolving() to supply custom (un)marshalling logic#7

Merged
thekid merged 2 commits intomasterfrom
feature/usertype-mapping
Nov 1, 2024
Merged

Add mapping() and resolving() to supply custom (un)marshalling logic#7
thekid merged 2 commits intomasterfrom
feature/usertype-mapping

Conversation

@thekid
Copy link
Copy Markdown
Member

@thekid thekid commented Nov 1, 2024

Given the following user type:

class User {
  public function __construct(public int $id, public string $name) { }
}

Defaults

$marshalling= new Marshalling();
$value= $marshalling->marshal(new User(0, 'root'));
// ['id' => 0, 'name' => 'root']

$user= $marshalling->unmarshal($value, User::class);
// User(id: 0, name: 'root')

Custom logic

$marshalling= (new Marshalling())
  ->mapping(User::class, fn($user) => ['uid' => $user->id])
  ->resolving(User::class, fn($value) => new User($value['uid'], posix_getpwuid($value['uid'])['name'])
;
$value= $marshalling->marshal(new User(0, 'root'));
// ['uid' => 0]

$user= $marshalling->unmarshal($value, User::class);
// User(id: 0, name: 'root')

@thekid thekid merged commit c3fbee8 into master Nov 1, 2024
@thekid thekid deleted the feature/usertype-mapping branch November 1, 2024 11:29
@thekid
Copy link
Copy Markdown
Member Author

thekid commented Nov 1, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant