mark-gerarts / automapper-plus

An AutoMapper for PHP
MIT License
551 stars 30 forks source link

Mapping string into DateTimeImmutable #80

Open alvaro-octal opened 2 years ago

alvaro-octal commented 2 years ago

Hi,

I was taking a look at the issues, but haven't found any similar, is there a way to map a string into a DateTime/DateTimeImmutable by default? I mean, I have the following entity:

class UserFilter
{
    public ?string $email = null; // this is beeing auto mapped
    public ?array $roleIds = null; // this need to be handled with forMember, OK
    public ?DateTimeImmutable $createdAt = null; // Could this be mapped without a forMember?
}

And by using this mapper it results in a error, because the library is not able to determine a mapper for string to DateTimeImmutable of the createdAt property.

$this->config->registerMapping(DataType::ARRAY, UserFilter::class)
        ->forMember('roleIds', MapperHelper::ArrayOfInt('roleIds'));
return $this->mapper->map($params, UserFilter::class);
Message: Cannot assign string to property App\Application\Actions\User\Request\_Filter\UserFilter::$createdAt of type ?DateTimeImmutable

File: /var/www/vendor/mark-gerarts/auto-mapper-plus/src/PropertyAccessor/PropertyAccessor.php

Line: 50

Trace: #0 /var/www/vendor/mark-gerarts/auto-mapper-plus/src/MappingOperation/DefaultMappingOperation.php(106): AutoMapperPlus\PropertyAccessor\PropertyAccessor->setProperty(Object(App\Application\Actions\User\Request\_Filter\UserFilter), 'createdAt', '2021-11-02')

#1 /var/www/vendor/mark-gerarts/auto-mapper-plus/src/MappingOperation/DefaultMappingOperation.php(52): AutoMapperPlus\MappingOperation\DefaultMappingOperation->setDestinationValue(Object(App\Application\Actions\User\Request\_Filter\UserFilter), 'createdAt', '2021-11-02')

Of course I can add another forMember in order to map the string into a DateTimeImmutable but seems repetitive to me, is there a way to automate?

mark-gerarts commented 2 years ago

No, this is not possible currently. If you have multiple recurring properties (createdAt, changedAt, deletedAt, ...), you could use copyMapping.

I can see the usefulness though, in a more generic sense: if a mapping exists from source type A to destination type B, automatically apply it. I am afraid that this is not a trivial thing to implement, especially for this case, since we're mapping from a scalar value to an object, which is something that still needs to be implemented as well.

I like the idea and will leave this open as food for thought.

alvaro-octal commented 2 years ago

Ok, thanks!