Skip to content

Instantly share code, notes, and snippets.

@Pierstoval
Created November 22, 2022 13:06
Show Gist options
  • Save Pierstoval/eba25f9245658102c318d6f0316a8110 to your computer and use it in GitHub Desktop.
Save Pierstoval/eba25f9245658102c318d6f0316a8110 to your computer and use it in GitHub Desktop.
<?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