Lemon-Framework / Lemon

🍋 A php microframework
https://lemon-framework.github.io/docs/
GNU General Public License v3.0
24 stars 8 forks source link

New DataMapper Component #129

Closed tenmajkl closed 1 year ago

tenmajkl commented 1 year ago

This PR adds new DataMapper component, which allows us to map data from associative array to class by its constructor. If the data are bad, it would return null, so we can use it as validator.

Example:

class User
{
    public function __construct(
        public readonly string $name,
        public readonly string $email,
    ) {

    }
}

class Book
{
    public function __construct(
        public readonly string $name,
        public readonly User $user,
        public readonly int $time,
    ) {

    }
}

Now if we have this data:

$data = [
    'name' => 'Jak prestat prokrastinovat',
    'user' => [
        'name' => 'Modry vak',
        'email' => 'tenmajkl@proton.me'
    ],
    'time' => 124125634745856,
];

We can simply pass them into DataMapper::mapTo($data, Book::class).

As you can see, it maps nested objects and it can handle several types.

We can also use Request::mapTo() which maps data from request, and if it goes wrong, it suspends route with fallback value on second argument.

TODO check array types.