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