automapper icon indicating copy to clipboard operation
automapper copied to clipboard

Wrong Type used for classes using Covariance

Open nicoschwartz opened this issue 1 year ago • 0 comments

Hi there!

First thank you for maintaining this project 🙏

While upgrading from automapper+automapper-bundle (8.1.0+8.0.2) to automapper 9.1.2 I ran into an issue with wrong type being used for properties of a target.

From what I've debugged and tested I think the setter of a property is used to determine the type of the target but it doesn't make much sense in case of covariance - covariance on php.net - as the return type of the getter can be more specific while the type in the signature of the setter cannot.

Here's the solution that worked for covariance's case : changing the SourceTargetMappingExtractor from : $targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty->property, [ReadWriteTypeExtractor::WRITE_MUTATOR => $targetProperty->writeMutator]) ?? []; to $targetTypes = $this->propertyInfoExtractor->getTypes($target, $targetProperty->property, [ReadWriteTypeExtractor::READ_ACCESSOR => $targetProperty->readAccessor]) ?? []; That way it uses the getter to determine the type which makes more sense (at least in this case).

It solves my case ... but breaks some other tests I ran from automapper's repo.

I wrote some tests with basic classes to show the issue, it's available here

nicoschwartz avatar Sep 26 '24 10:09 nicoschwartz