|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ntb\RestAPI; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* The nested resource controller can help you to avoid some boilerplate in nested resources in you rest api. |
|
7
|
|
|
* |
|
8
|
|
|
* If you have a resource `user` and the endpoint `/users` then a nested resource could be the friends of a specific |
|
9
|
|
|
* user. `/users/1/friends` is a possible endpoint for that. In every method you first need to check if the user with the |
|
10
|
|
|
* id 1 is available in the system. |
|
11
|
|
|
* |
|
12
|
|
|
* The friends controller can extend the nested resource rest controller and is now able to handle request in an easier |
|
13
|
|
|
* way. |
|
14
|
|
|
* |
|
15
|
|
|
* @author Christian Blank <[email protected]> |
|
16
|
|
|
*/ |
|
17
|
|
|
abstract class NestedResourceRestController extends BaseRestController { |
|
18
|
|
|
/** |
|
19
|
|
|
* @var string the error message if no id was provided for the request |
|
20
|
|
|
*/ |
|
21
|
|
|
protected static $no_id_message = "No id provided."; |
|
22
|
|
|
/** |
|
23
|
|
|
* @var int the error code for a not provided id |
|
24
|
|
|
*/ |
|
25
|
|
|
protected static $no_id_error = 404; |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* Get called by the action handler of BaseRestController. Tries to fetch the root resource. |
|
29
|
|
|
* |
|
30
|
|
|
* @param \SS_HTTPRequest $request a http request |
|
31
|
|
|
* @param string $action the name of the action (eg. post, put, get, delete) |
|
32
|
|
|
* @return array the result of the action call |
|
33
|
|
|
* @throws RestSystemException |
|
34
|
|
|
* @throws RestUserException |
|
35
|
|
|
*/ |
|
36
|
|
|
public final function beforeCallActionHandler(\SS_HTTPRequest $request, $action) { |
|
37
|
|
|
$id = $request->param(\Config::inst()->get('NestedResourceRestController', 'root_resource_id_field')); |
|
38
|
|
|
if(!$id) { |
|
39
|
|
|
throw new RestUserException(static::$no_id_message, static::$no_id_message); |
|
40
|
|
|
} |
|
41
|
|
|
$resource = $this->getRootResource($id); |
|
42
|
|
|
if(!$resource) { |
|
43
|
|
|
\SS_Log::log("NoResourceError was not handled inside the controller", \SS_Log::WARN); |
|
44
|
|
|
throw new RestSystemException("NoResourceError was not handled inside the controller", 501); |
|
45
|
|
|
} |
|
46
|
|
|
// call the action and inject the root resource |
|
47
|
|
|
return $this->$action($request, $resource); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* |
|
52
|
|
|
* The result of this method will be injected in all method calls in the controller. |
|
53
|
|
|
* |
|
54
|
|
|
* @param string $id the `ID` param in the request |
|
55
|
|
|
* @return mixed |
|
56
|
|
|
*/ |
|
57
|
|
|
protected abstract function getRootResource($id); |
|
58
|
|
|
|
|
59
|
|
|
} |
|
60
|
|
|
|