1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Phrest\API; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
trait RESTActionTrait |
7
|
|
|
{ |
8
|
|
|
use \Psr\Log\LoggerAwareTrait; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @var array |
12
|
|
|
*/ |
13
|
|
|
static private $methods = [ |
14
|
|
|
'get' => 'GET', |
15
|
|
|
'post' => 'POST', |
16
|
|
|
'put' => 'PUT', |
17
|
|
|
'delete' => 'DELETE', |
18
|
|
|
'patch' => 'PATCH', |
19
|
|
|
'options' => 'OPTIONS', |
20
|
|
|
]; |
21
|
|
|
|
22
|
3 |
|
public function process(\Psr\Http\Message\ServerRequestInterface $request, \Interop\Http\ServerMiddleware\DelegateInterface $delegate) |
|
|
|
|
23
|
|
|
{ |
24
|
3 |
|
$method = strtolower($request->getMethod()); |
25
|
|
|
|
26
|
3 |
|
$this->logger->debug(__METHOD__ . ' called', ['method' => $method]); |
27
|
|
|
|
28
|
3 |
|
if (!array_key_exists($method, self::$methods)) { |
29
|
1 |
|
$this->throwMethodNotAllowed($method); |
30
|
|
|
} |
31
|
|
|
|
32
|
2 |
|
if ($method === 'options') { |
33
|
1 |
|
return $this->options(); |
34
|
|
|
} |
35
|
|
|
|
36
|
1 |
|
return $this->onRESTRequest($request, $method); |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
private function options(): \Psr\Http\Message\ResponseInterface |
40
|
|
|
{ |
41
|
1 |
|
return new \Zend\Diactoros\Response\EmptyResponse( |
42
|
1 |
|
\Phrest\Http\StatusCodes::NO_CONTENT, |
43
|
|
|
[ |
44
|
1 |
|
'Allow' => implode(', ', $this->getAllowedMethods()) |
45
|
|
|
] |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
1 |
|
protected function onRESTRequest(\Psr\Http\Message\ServerRequestInterface $request, string $method): \Psr\Http\Message\ResponseInterface |
|
|
|
|
50
|
|
|
{ |
51
|
1 |
|
return new \Zend\Diactoros\Response\EmptyResponse(); |
52
|
|
|
} |
53
|
|
|
|
54
|
2 |
|
private function getAllowedMethods(): array |
55
|
|
|
{ |
56
|
2 |
|
$allowedMethods = []; |
57
|
|
|
|
58
|
|
|
/* @todo: Reflections? */ |
59
|
2 |
|
$ref = new \ReflectionClass($this); |
60
|
2 |
|
foreach ($ref->getMethods() as $methodRef) { |
61
|
2 |
|
if ($methodRef->class != self::class && array_key_exists($methodRef->name, self::$methods)) { |
62
|
2 |
|
$allowedMethods[] = self::$methods[$methodRef->name]; |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
return $allowedMethods; |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
private function throwMethodNotAllowed(string $method) |
70
|
|
|
{ |
71
|
1 |
|
throw \Phrest\Http\Exception::MethodNotAllowed( |
72
|
1 |
|
new \Phrest\API\Error( |
73
|
1 |
|
0, |
74
|
1 |
|
'Method not allowed', |
75
|
1 |
|
new \Phrest\API\ErrorEntry( |
76
|
1 |
|
0, |
77
|
1 |
|
'method', |
78
|
1 |
|
'Method "' . $method . '" not allowed', |
79
|
1 |
|
implode(', ', $this->getAllowedMethods()) |
80
|
|
|
) |
81
|
|
|
) |
82
|
|
|
); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.