1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Sensio\Bundle\FrameworkExtraBundle\Request;
13
14use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactoryInterface;
15use Symfony\Component\HttpKernel\Event\FilterControllerArgumentsEvent;
16
17/**
18 * @author Ryan Weaver <ryan@knpuniversity.com>
19 */
20class ArgumentNameConverter
21{
22    private $argumentMetadataFactory;
23
24    public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory)
25    {
26        $this->argumentMetadataFactory = $argumentMetadataFactory;
27    }
28
29    /**
30     * Returns an associative array of the controller arguments for the event.
31     *
32     * @param FilterControllerArgumentsEvent $event
33     *
34     * @return array
35     */
36    public function getControllerArguments(FilterControllerArgumentsEvent $event)
37    {
38        $namedArguments = $event->getRequest()->attributes->all();
39        $argumentMetadatas = $this->argumentMetadataFactory->createArgumentMetadata($event->getController());
40        $controllerArguments = $event->getArguments();
41
42        foreach ($argumentMetadatas as $index => $argumentMetadata) {
43            if ($argumentMetadata->isVariadic()) {
44                // set the rest of the arguments as this arg's value
45                $namedArguments[$argumentMetadata->getName()] = array_slice($controllerArguments, $index);
46
47                break;
48            }
49
50            if (!array_key_exists($index, $controllerArguments)) {
51                throw new \LogicException(sprintf('Could not find an argument value for argument %d of the controller.', $index));
52            }
53
54            $namedArguments[$argumentMetadata->getName()] = $controllerArguments[$index];
55        }
56
57        return $namedArguments;
58    }
59}
60