Advertisement
toaspzoo

PHP Array to DTO

May 25th, 2020
2,667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.06 KB | None | 0 0
  1. /**
  2.      * @param array $input []
  3.      * @param Dto $target_class
  4.      * @return $source_class[]
  5.      * @throws ReflectionException
  6.      */
  7.     private function toDTO($input, $target_class)
  8.     {
  9.         $input = json_decode(json_encode((array)$input), true);
  10.         $dtoResults = [];
  11.  
  12.         foreach ($input as $singleInput) {
  13.             $out = new ReflectionClass($target_class);
  14.             $out = $out->newInstance();
  15.  
  16.             if (!$out instanceof Dto) {
  17.                 return ['Class is not Dto'];
  18.             }
  19.  
  20.             $fields = get_class_vars($target_class);
  21.             $setters = [];
  22.             foreach ($fields as $field => $v) {
  23.                 $setters[] = ['setter' => OmegaService::camelCase("set_" . $field), 'value' => $singleInput[$field]];
  24.             }
  25.  
  26.             foreach ($setters as $setter) {
  27.                 $call = new ReflectionMethod($out, $setter['setter']);
  28.                 $call->invokeArgs($out, [$setter['value']]);
  29.             }
  30.  
  31.             $dtoResults[] = $out;
  32.         }
  33.  
  34.         return $dtoResults;
  35.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement