1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Phprest\Router; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Hateoas\Hateoas; |
7
|
|
|
use League\Container\ContainerInterface; |
8
|
|
|
use League\Route\Strategy\AbstractStrategy; |
9
|
|
|
use League\Route\Strategy\StrategyInterface; |
10
|
|
|
use Phprest\HttpFoundation\Response; |
11
|
|
|
use Phprest\Service; |
12
|
|
|
use Symfony\Component\HttpFoundation\Request; |
13
|
|
|
|
14
|
|
|
class Strategy extends AbstractStrategy implements StrategyInterface |
15
|
|
|
{ |
16
|
|
|
use Service\Hateoas\Util; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var ContainerInterface |
20
|
|
|
*/ |
21
|
|
|
protected $container; |
22
|
|
|
|
23
|
228 |
|
/** |
24
|
|
|
* @param ContainerInterface $container |
25
|
228 |
|
*/ |
26
|
228 |
|
public function __construct(ContainerInterface $container) |
27
|
|
|
{ |
28
|
|
|
$this->container = $container; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Dispatch the controller, the return value of this method will bubble out and be |
33
|
|
|
* returned by \League\Route\Dispatcher::dispatch, it does not require a response, however, |
34
|
|
|
* beware that there is no output buffering by default in the router. |
35
|
|
|
* |
36
|
|
|
* $controller can be one of three types but based on the type you can infer what the |
37
|
|
|
* controller actually is: |
38
|
|
|
* - string (controller is a named function) |
39
|
|
|
* - array (controller is a class method [0 => ClassName, 1 => MethodName]) |
40
|
|
|
* - \Closure (controller is an anonymous function) |
41
|
|
|
* |
42
|
|
|
* @param string|array|Closure $controller |
43
|
|
|
* @param array $vars - named wildcard segments of the matched route |
44
|
12 |
|
* |
45
|
|
|
* @return mixed |
46
|
12 |
|
*/ |
47
|
|
|
public function dispatch($controller, array $vars) |
48
|
12 |
|
{ |
49
|
12 |
|
$request = $this->container->get(Request::class); |
50
|
12 |
|
|
51
|
|
|
$response = $this->invokeController($controller, array_merge( |
52
|
|
|
[$request], |
53
|
12 |
|
array_values($vars) |
54
|
3 |
|
)); |
55
|
3 |
|
|
56
|
2 |
|
if ($response instanceof Response && $response->getContent() !== '') { |
57
|
2 |
|
return $this->serialize( |
58
|
|
|
$response->getContent(), |
59
|
|
|
$request, |
60
|
|
|
$response |
61
|
9 |
|
); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $response; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return Hateoas |
69
|
|
|
* |
70
|
|
|
* @codeCoverageIgnore |
71
|
|
|
*/ |
72
|
|
|
protected function serviceHateoas(): Hateoas |
73
|
|
|
{ |
74
|
|
|
return $this->getContainer()->get(Service\Hateoas\Config::getServiceName()); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|