Skip to content

Instantly share code, notes, and snippets.

@daler445
Created October 13, 2021 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daler445/6252af938afec1fd9e45d1666ff557cc to your computer and use it in GitHub Desktop.
Save daler445/6252af938afec1fd9e45d1666ff557cc to your computer and use it in GitHub Desktop.
Array to object mapper
<?php
declare(strict_types=1);
class Converter
{
/**
* @param array $array
* @param $object
* @return object
* @throws \RuntimeException
*/
public static function toObject(array $array, $object): object
{
if (PHP_VERSION_ID < 80000) {
throw new RuntimeException('PHP version must be 8+');
}
try {
$class = new ReflectionClass($object);
$methods = $class->getMethods();
if ($methods === null || count($methods) === 0) {
throw new RuntimeException('No methods available');
}
foreach ($methods as $method) {
preg_match('/^(set)(.*?)$/i', $method->getName(), $results);
$pre = $results[1] ?? '';
$k = $results[2] ?? '';
if ($pre !== 'set') {
continue;
}
$k = strtolower(substr($k, 0, 1) . substr($k, 1));
if (!isset($array[$k])) {
continue;
}
$parameters = $method->getParameters();
$paramCount = count($parameters);
if ($paramCount === 0 || $paramCount > 1) {
continue;
}
$param = $parameters[0];
$methodName = $method->getName();
$value = $array[$k];
settype($value, $param->getType());
$object->$methodName($array[$k], $value);
}
return $object;
} catch (ReflectionException $e) {
throw new RuntimeException('Failed to reflect');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment