|
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()); |
|
|
|
|
|
|
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
|
|
|
|
Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.