Created
November 22, 2022 13:06
-
-
Save Pierstoval/eba25f9245658102c318d6f0316a8110 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class RawObjectMapper | |
{ | |
public static function mapObjects(string $targetClassName, object $sourceObject): object | |
{ | |
$sourceClass = \get_class($sourceObject); | |
$targetObject = (new \Doctrine\Instantiator\Instantiator())->instantiate($targetClassName); | |
$setter = \Closure::bind(static function (string $property, $value) use ($targetObject, $targetClassName): void { | |
if (!\property_exists($targetObject, $property)) { | |
throw new \InvalidArgumentException( | |
\sprintf( | |
'Cannot set property "%s" to "%s" object since this property does not exist.', | |
$property, | |
$targetClassName | |
) | |
); | |
} | |
$targetObject->{$property} = $value; | |
}, null, $targetClassName); | |
$getter = function (string $property) use ($sourceObject, $sourceClass): mixed { | |
if (!\property_exists($sourceObject, $property)) { | |
throw new \InvalidArgumentException( | |
\sprintf( | |
'Cannot get value of property "%s" to "%s" object since this property does not exist.', | |
$property, | |
$sourceClass | |
) | |
); | |
} | |
return $sourceObject->{$property}; | |
}; | |
$refl = new \ReflectionClass($sourceClass); | |
foreach ($refl->getProperties() as $reflProperty) { | |
$property = $reflProperty->getName(); | |
$setter($property, $getter($property)); | |
} | |
return $targetObject; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment