Test Setup Failed
Push — master ( 1a9491...b3bb4f )
by Pascal
09:30
created

ChainRequestMatcher::matchRequest()   B

Complexity

Conditions 6
Paths 12

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
cc 6
eloc 16
nc 12
nop 1
1
<?php
2
3
namespace Skalpa\Silex\Symfony\Routing;
4
5
use Symfony\Component\HttpFoundation\Request;
6
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
7
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
8
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
9
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
10
11
/**
12
 * Calls several request matchers until one successfully recognizes the request.
13
 */
14
class ChainRequestMatcher implements RequestMatcherInterface
15
{
16
    private $matchers;
17
18
    /**
19
     * @param RequestMatcherInterface[]|UrlMatcherInterface[] ...$matchers
20
     */
21
    public function __construct(...$matchers)
22
    {
23
        foreach ($matchers as $matcher) {
24
            if (!$matcher instanceof RequestMatcherInterface && !$matcher instanceof UrlMatcherInterface) {
25
                throw new \InvalidArgumentException(sprintf('Invalid request matcher. Expected an instance of %s or %s, got %s.', RequestMatcherInterface::class, UrlMatcherInterface::class, is_object($matcher) ? get_class($matcher) : gettype($matcher)));
26
            }
27
        }
28
        $this->matchers = $matchers;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function matchRequest(Request $request)
35
    {
36
        /** @var ResourceNotFoundException $notFound */
37
        $notFound = null;
38
        /** @var MethodNotAllowedException $badMethod */
39
        $badMethod = null;
40
41
        foreach ($this->matchers as $matcher) {
42
            try {
43
                if ($matcher instanceof RequestMatcherInterface) {
44
                    return $matcher->matchRequest($request);
45
                } else {
46
                    return $matcher->match($request->getPathInfo());
0 ignored issues
show
Bug introduced by
The method match cannot be called on $matcher (of type array<integer,object<Sym...r\UrlMatcherInterface>>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
47
                }
48
            } catch (ResourceNotFoundException $e) {
49
                $notFound = $e;
50
            } catch (MethodNotAllowedException $e) {
51
                $badMethod = $e;
52
            }
53
        }
54
55
        if (null !== $badMethod) {
56
            // If a matcher recognized the URL but not the method, this takes precedence
57
            throw $badMethod;
58
        }
59
        // Otherwise, re-throw the last ResourceNotFoundException
60
        throw $notFound;
61
    }
62
}
63