diff --git a/src/Laracasts/Commander/CommanderTrait.php b/src/Laracasts/Commander/CommanderTrait.php index 688768a..aa39748 100644 --- a/src/Laracasts/Commander/CommanderTrait.php +++ b/src/Laracasts/Commander/CommanderTrait.php @@ -56,17 +56,43 @@ public function getCommandBus() */ protected function mapInputToCommand($command, array $input) { - $dependencies = []; - $class = new ReflectionClass($command); + if(!$class->getConstructor()) + { + return $this->mapInputToCommandProperties($class, $input); + } + else + { + return $this->mapInputToCommandConstructor($class, $input); + } + } + + /** + * @param ReflectionClass $class + * @param $input + * @return object + * @throws \InvalidArgumentException + */ + protected function mapInputToCommandConstructor(ReflectionClass $class, array $input) + { + $dependencies = []; + foreach ($class->getConstructor()->getParameters() as $parameter) { $name = $parameter->getName(); if (array_key_exists($name, $input)) { - $dependencies[] = $input[$name]; + if($parameter->getClass() !== null) + { + $className = $parameter->getClass()->getName(); + $dependencies[] = new $className($input[$name]); + } + else + { + $dependencies[] = $input[$name]; + } } elseif ($parameter->isDefaultValueAvailable()) { @@ -79,6 +105,30 @@ protected function mapInputToCommand($command, array $input) } return $class->newInstanceArgs($dependencies); + + } + + /** + * @param ReflectionClass $class + * @param $input + * @throws \InvalidArgumentException + * @return object + */ + protected function mapInputToCommandProperties(ReflectionClass $class, array $input) + { + $command = $class->newInstance(); + + foreach($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) + { + $name = $property->getName(); + + if(array_key_exists($name, $input)) + { + $command->{$name} = $input[$name]; + } + } + + return $command; } }