4 * This file is part of the Behat.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Behat\HelperContainer;
13 use Psr\Container\ContainerExceptionInterface;
14 use Psr\Container\ContainerInterface;
15 use ReflectionFunctionAbstract;
16 use ReflectionParameter;
19 * Automatically wires arguments of a given function from inside the container by using type-hitns.
21 * @author Konstantin Kudryashov <ever.zet@gmail.com>
23 final class ArgumentAutowirer
26 * @var ContainerInterface
33 * @param ContainerInterface $container
35 public function __construct(ContainerInterface $container)
37 $this->container = $container;
41 * Autowires given arguments using provided container.
43 * @param ReflectionFunctionAbstract $reflection
44 * @param array $arguments
48 * @throws ContainerExceptionInterface if unset argument typehint can not be resolved from container
50 public function autowireArguments(ReflectionFunctionAbstract $reflection, array $arguments)
52 $newArguments = $arguments;
53 foreach ($reflection->getParameters() as $index => $parameter) {
54 if ($this->isArgumentWireable($newArguments, $index, $parameter)) {
55 $newArguments[$index] = $this->container->get($parameter->getClass()->getName());
63 * Checks if given argument is wireable.
65 * Argument is wireable if it was not previously set and it has a class type-hint.
67 * @param array $arguments
68 * @param integer $index
69 * @param ReflectionParameter $parameter
73 private function isArgumentWireable(array $arguments, $index, ReflectionParameter $parameter)
75 return !isset($arguments[$index]) && !isset($arguments[$parameter->getName()]) && $parameter->getClass();