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
|
75 |
|
public function invoke(AbstractRequest $request) |
39
|
|
|
{ |
40
|
75 |
|
$onMethod = 'on' . ucfirst($request->method); |
41
|
75 |
|
if (method_exists($request->resourceObject, $onMethod) === true) { |
42
|
64 |
|
return $this->invokeMethod($request, $onMethod); |
43
|
|
|
} |
44
|
11 |
|
if ($request->method === Request::OPTIONS) { |
45
|
8 |
|
return $this->invokeOptions($request); |
46
|
|
|
} |
47
|
|
|
|
48
|
3 |
|
throw new MethodNotAllowedException(get_class($request->resourceObject) . "::{($request->method}()", 405); |
49
|
|
|
} |
50
|
|
|
|
51
|
64 |
|
private function invokeMethod(AbstractRequest $request, string $onMethod) : ResourceObject |
52
|
|
|
{ |
53
|
64 |
|
if ($request->resourceObject->uri instanceof AbstractUri) { |
54
|
40 |
|
$request->resourceObject->uri->query = $request->query; |
55
|
40 |
|
$request->resourceObject->uri->method = $request->method; |
56
|
|
|
} |
57
|
64 |
|
$params = $this->params->getParameters([$request->resourceObject, $onMethod], $request->query); |
58
|
60 |
|
$response = call_user_func_array([$request->resourceObject, $onMethod], $params); |
59
|
|
|
|
60
|
57 |
|
if (! $response instanceof ResourceObject) { |
61
|
30 |
|
$request->resourceObject->body = $response; |
62
|
30 |
|
$response = $request->resourceObject; |
63
|
|
|
} |
64
|
|
|
|
65
|
57 |
|
return $response; |
66
|
|
|
} |
67
|
|
|
|
68
|
8 |
|
private function invokeOptions(AbstractRequest $request) : ResourceObject |
69
|
|
|
{ |
70
|
8 |
|
$ro = $request->resourceObject; |
71
|
8 |
|
$ro->view = $this->optionsRenderer->render($request->resourceObject); |
72
|
|
|
|
73
|
7 |
|
return $ro; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|