Created
October 13, 2021 05:34
-
-
Save daler445/6252af938afec1fd9e45d1666ff557cc to your computer and use it in GitHub Desktop.
Array to object mapper
This file contains hidden or 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 | |
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