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
|
|
|
final class OptionProvider implements OptionProviderInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* Valid resource request methods |
13
|
|
|
* |
14
|
|
|
* @var array |
15
|
|
|
*/ |
16
|
|
|
const VALID_METHODS = ['onGet', 'onPost', 'onPut', 'onPatch', 'onDelete', 'onHead']; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* {@inheritdoc} |
20
|
|
|
*/ |
21
|
3 |
|
public function get(ResourceObject $ro) |
22
|
|
|
{ |
23
|
3 |
|
$options = $this->getOptions($ro); |
24
|
|
|
$ro->headers['allow'] = (string) $options; |
25
|
|
|
$ro->body = null; |
26
|
|
|
|
27
|
|
|
return $ro; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Return available resource request method |
32
|
|
|
* |
33
|
|
|
* @param ResourceObject $resourceObject |
34
|
|
|
* |
35
|
|
|
* @return Options |
36
|
|
|
*/ |
37
|
3 |
|
private function getOptions(ResourceObject $resourceObject) |
38
|
|
|
{ |
39
|
3 |
|
$allows = $this->getAllows((new \ReflectionClass($resourceObject))->getMethods()); |
40
|
|
|
$params = []; |
41
|
|
|
foreach ($allows as $method) { |
42
|
|
|
$params[] = $this->getParams($resourceObject, $method); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return new Options($allows, $params); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param \ReflectionMethod[] $methods |
50
|
|
|
* |
51
|
|
|
* @return array |
52
|
|
|
*/ |
53
|
3 |
|
private function getAllows(array $methods) |
54
|
|
|
{ |
55
|
3 |
|
$allows = []; |
56
|
3 |
|
foreach ($methods as $method) { |
57
|
3 |
|
if (in_array($method->name, self::AVAILABLE_METHODS)) { |
58
|
|
|
$allows[] = strtolower(substr($method->name, 2)); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return $allows; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param ResourceObject $ro |
67
|
|
|
* @param string $method |
68
|
|
|
* |
69
|
|
|
* @return string[] |
70
|
|
|
*/ |
71
|
|
|
private function getParams($ro, $method) |
72
|
|
|
{ |
73
|
|
|
$params = []; |
74
|
|
|
$refMethod = new \ReflectionMethod($ro, 'on' . $method); |
75
|
|
|
$parameters = $refMethod->getParameters(); |
76
|
|
|
$paramArray = []; |
77
|
|
|
foreach ($parameters as $parameter) { |
78
|
|
|
$name = $parameter->name; |
79
|
|
|
$param = $parameter->isOptional() ? "({$name})" : $name; |
80
|
|
|
$paramArray[] = $param; |
81
|
|
|
} |
82
|
|
|
$key = "param-{$method}"; |
83
|
|
|
$params[$key] = implode(',', $paramArray); |
84
|
|
|
|
85
|
|
|
return $params; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|