1 | <?php |
||
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 |