SHARE
TWEET

PHP Array to DTO

toaspzoo May 25th, 2020 1,748 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.     }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top