|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* This file is part of the BEAR.Resource package. |
|
4
|
|
|
* |
|
5
|
|
|
* @license http://opensource.org/licenses/MIT MIT |
|
6
|
|
|
*/ |
|
7
|
|
|
namespace BEAR\Resource; |
|
8
|
|
|
|
|
9
|
|
|
use BEAR\Resource\Exception\MethodNotAllowedException; |
|
10
|
|
|
use Ray\Di\Di\Named; |
|
11
|
|
|
|
|
12
|
|
|
final class Invoker implements InvokerInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var NamedParameterInterface |
|
16
|
|
|
*/ |
|
17
|
|
|
private $params; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var RenderInterface |
|
21
|
|
|
*/ |
|
22
|
|
|
private $optionsRenderer; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @Named("optionsRenderer=options") |
|
26
|
|
|
*/ |
|
27
|
95 |
|
public function __construct(NamedParameterInterface $params, RenderInterface $optionsRenderer) |
|
28
|
|
|
{ |
|
29
|
95 |
|
$this->params = $params; |
|
30
|
95 |
|
$this->optionsRenderer = $optionsRenderer; |
|
31
|
95 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritdoc} |
|
35
|
|
|
* |
|
36
|
|
|
* @throws MethodNotAllowedException |
|
37
|
|
|
*/ |
|
38
|
71 |
|
public function invoke(AbstractRequest $request) |
|
39
|
|
|
{ |
|
40
|
71 |
|
$onMethod = 'on' . ucfirst($request->method); |
|
41
|
71 |
|
if (method_exists($request->resourceObject, $onMethod) === true) { |
|
42
|
11 |
|
return $this->invokeMethod($request, $onMethod); |
|
43
|
|
|
} |
|
44
|
60 |
|
if ($request->method === Request::OPTIONS) { |
|
45
|
36 |
|
return $this->invokeOptions($request); |
|
46
|
36 |
|
} |
|
47
|
|
|
|
|
48
|
60 |
|
throw new MethodNotAllowedException(get_class($request->resourceObject) . "::{($request->method}()", 405); |
|
49
|
56 |
|
} |
|
50
|
|
|
|
|
51
|
55 |
|
private function invokeMethod(AbstractRequest $request, string $onMethod) : ResourceObject |
|
52
|
|
|
{ |
|
53
|
|
|
if ($request->resourceObject->uri instanceof AbstractUri) { |
|
54
|
|
|
$request->resourceObject->uri->query = $request->query; |
|
55
|
|
|
$request->resourceObject->uri->method = $request->method; |
|
56
|
|
|
} |
|
57
|
|
|
$params = $this->params->getParameters([$request->resourceObject, $onMethod], $request->query); |
|
58
|
55 |
|
$response = call_user_func_array([$request->resourceObject, $onMethod], $params); |
|
59
|
|
|
|
|
60
|
55 |
|
if (! $response instanceof ResourceObject) { |
|
61
|
30 |
|
$request->resourceObject->body = $response; |
|
62
|
30 |
|
$response = $request->resourceObject; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
55 |
|
return $response; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
private function invokeOptions(AbstractRequest $request) : ResourceObject |
|
69
|
|
|
{ |
|
70
|
|
|
$ro = $request->resourceObject; |
|
71
|
|
|
$ro->view = $this->optionsRenderer->render($request->resourceObject); |
|
72
|
|
|
|
|
73
|
11 |
|
return $ro; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|