Completed
Push — 2.0 ( e69d85...2b1775 )
by Kévin
19s
created

RouteNameResolver   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
c 0
b 0
f 0
lcom 1
cbo 4
dl 0
loc 29
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B getRouteName() 0 16 7
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Symfony\Routing;
15
16
use ApiPlatform\Core\Exception\InvalidArgumentException;
17
use Symfony\Component\Routing\RouterInterface;
18
19
/**
20
 * {@inheritdoc}
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 */
24
final class RouteNameResolver implements RouteNameResolverInterface
25
{
26
    private $router;
27
28
    public function __construct(RouterInterface $router)
29
    {
30
        $this->router = $router;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function getRouteName(string $resourceClass, bool $collection): string
37
    {
38
        $operationType = $collection ? 'collection' : 'item';
39
40
        foreach ($this->router->getRouteCollection()->all() as $routeName => $route) {
41
            $currentResourceClass = $route->getDefault('_api_resource_class');
42
            $operation = $route->getDefault(sprintf('_api_%s_operation_name', $operationType));
43
            $methods = $route->getMethods();
44
45
            if ($resourceClass === $currentResourceClass && null !== $operation && (empty($methods) || in_array('GET', $methods, true))) {
46
                return $routeName;
47
            }
48
        }
49
50
        throw new InvalidArgumentException(sprintf('No %s route associated with the type "%s".', $operationType, $resourceClass));
51
    }
52
}
53