Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
RestBaseController.php
Go to the documentation of this file.
1<?php
2
4
15
26
27 protected $config;
28 protected $model;
29 protected $contentType;
30 protected $restCache;
31 protected $useValidation = true;
32
43
48 protected $server;
49
50 public function __construct() {
51 if (!\headers_sent()) {
52 @\set_exception_handler(array($this, '_errorHandler'));
53 $this->config = Startup::getConfig();
54 $this->server = $this->_getRestServer();
55 $this->server->cors();
56 $this->responseFormatter = $this->_getResponseFormatter();
57 $this->requestFormatter = $this->_getRequestFormatter();
58 $this->server->_setContentType($this->contentType);
59 $this->restCache = CacheManager::getRestCacheController(\get_class($this));
60 }
61 if (!$this->isValid(Startup::getAction()))
62 $this->onInvalidControl();
63 }
64
65 public function index() {
66 $routesPath = Router::getRoutesPathByController(get_class($this));
67 echo $this->_getResponseFormatter()->format(['links' => $routesPath]);
68 }
69
70 public function isValid($action) {
71 if (isset ($this->restCache ['authorizations'])) {
72 if (\array_search($action, $this->restCache ['authorizations']) !== false) {
73 return $this->server->isValid(function ($datas = null) use ($action) {
74 return $this->checkPermissions($action, $datas);
75 });
76 }
77 }
78 return true;
79 }
80
90 protected function checkPermissions($action, $datas = null): bool {
91 return true;
92 }
93
100 protected function requireAuth($action): bool {
101 if (isset ($this->restCache ["authorizations"])) {
102 return \array_search($action, $this->restCache ["authorizations"]) !== false;
103 }
104 return false;
105 }
106
107 public function onInvalidControl() {
108 throw new \Exception ('HTTP/1.1 401 Unauthorized, you need an access token for this request', 401);
109 }
110
115 public function connect() {
116 $datas = null;
117 $resp = $this->server->connect($datas);
118 echo $this->_format($resp);
119 }
120
125 protected function refreshToken() {
126 $resp = $this->server->refreshToken();
127 echo $this->_format($resp);
128 }
129
130 public function initialize() {
131 }
132
133 public function finalize() {
134 parent::finalize();
135 $this->server->finalizeTokens();
136 }
137
138 public function _errorHandler($e) {
139 $this->_setResponseCode(Router::getStatusCode());
140 echo $this->_getResponseFormatter()->formatException($e);
141 }
142
143 public function _setResponseCode($value) {
144 \http_response_code($value);
145 }
146
154 public function _get($condition = '1=1', $include = false, $useCache = false) {
155 try {
156 $condition = $this->getCondition($condition);
157 $include = $this->getInclude($include);
158 $useCache = UString::isBooleanTrue($useCache);
159 $datas = DAO::getAll($this->model, $condition, $include, null, $useCache);
160 echo $this->_getResponseFormatter()->get($datas);
161 } catch (\Exception $e) {
162 $this->_setResponseCode(500);
163 echo $this->_getResponseFormatter()->formatException($e);
164 }
165 }
166
175 public function _getAll() {
176 $filter = $this->getCondition($this->getRequestParam('filter', '1=1'));
177 $pages = null;
178 if (isset ($_GET ['page'])) {
179 $pageNumber = $_GET ['page'] ['number'];
180 $pageSize = $_GET ['page'] ['size'] ?? 1;
181 $pages = $this->generatePagination($filter, $pageNumber, $pageSize);
182 }
183 $datas = DAO::getAll($this->model, $filter, $this->getInclude($this->getRequestParam('include', false)));
184 EventsManager::trigger(RestEvents::BEFORE_GET_ALL, $datas, $this);
185 echo $this->_getResponseFormatter()->get($datas, $pages);
186 }
187
195 public function _getOne($keyValues, $include = false, $useCache = false) {
196 $keyValues = $this->getCondition($keyValues);
197 $include = $this->getInclude($include);
198 $useCache = UString::isBooleanTrue($useCache);
199 $data = DAO::getById($this->model, $keyValues, $include, $useCache);
200 EventsManager::trigger(RestEvents::BEFORE_GET_ONE, $data, $this);
201 if (isset ($data)) {
202 $_SESSION ["_restInstance"] = $data;
203 echo $this->_getResponseFormatter()->getOne($data);
204 } else {
205 $this->_setResponseCode(404);
206 echo $this->_getResponseFormatter()->format(RestError::notFound($keyValues, "RestController/getOne")->asArray());
207 }
208 }
209
210 public function _format($arrayMessage) {
211 return $this->_getResponseFormatter()->format($arrayMessage);
212 }
213
221 public function _getManyToOne($ids, $member, $include = false, $useCache = false) {
222 $this->getAssociatedMemberValues_($ids, function ($instance, $member, $include, $useCache) {
223 return DAO::getManyToOne($instance, $member, $include, $useCache);
224 }, $member, $include, $useCache, false);
225 }
226
235 public function _getOneToMany($ids, $member, $include = false, $useCache = false) {
236 $this->getAssociatedMemberValues_($ids, function ($instance, $member, $include, $useCache) {
237 return DAO::getOneToMany($instance, $member, $include, $useCache);
238 }, $member, $include, $useCache, true);
239 }
240
249 public function _getManyToMany($ids, $member, $include = false, $useCache = false) {
250 $this->getAssociatedMemberValues_($ids, function ($instance, $member, $include, $useCache) {
251 return DAO::getManyToMany($instance, $member, $include, null, $useCache);
252 }, $member, $include, $useCache, true);
253 }
254
261 public function _update(...$keyValues) {
262 $instance = DAO::getById($this->model, $keyValues, false);
263 $this->operate_($instance, function ($instance) {
264 $datas = $this->getDatas();
265 $this->_setValuesToObject($instance, $datas);
266 EventsManager::trigger(RestEvents::BEFORE_UPDATE, $instance, $datas, $this);
267 if ($this->_validateInstance($instance, \array_keys($datas))) {
268 return $this->updateOperation($instance, $datas, true);
269 }
270 return null;
271 }, 'updated', 'Unable to update the instance', $keyValues);
272 }
273
278 public function _add() {
279 $model = $this->model;
280 $instance = new $model ();
281 $this->operate_($instance, function ($instance) use ($model) {
282 $datas = $this->getDatas();
283 $this->_setValuesToObject($instance, $datas);
284 EventsManager::trigger(RestEvents::BEFORE_INSERT, $instance, $datas, $this);
285 $fields = \array_keys(OrmUtils::getSerializableFields($model));
286 if ($this->_validateInstance($instance, $fields, ['id' => false])) {
287 $this->_setResponseCode(201);
288 return $this->addOperation($instance, $datas, true);
289 }
290 return null;
291 }, 'inserted', 'Unable to insert the instance', []);
292 }
293
303 public function _getRelationShip($id, $member) {
304 $relations = OrmUtils::getAnnotFieldsInRelations($this->model);
305 if (isset ($relations [$member])) {
306 $include = $this->getRequestParam('include', true);
307 switch ($relations [$member] ['type']) {
308 case 'manyToOne' :
309 $this->_getManyToOne($id, $member, $include);
310 break;
311 case 'oneToMany' :
312 $this->_getOneToMany($id, $member, $include);
313 break;
314 case 'manyToMany' :
315 $this->_getManyToMany($id, $member, $include);
316 break;
317 }
318 }
319 }
320
326 public function _delete(...$keyValues) {
327 $instance = DAO::getById($this->model, $keyValues, false);
328 $this->operate_($instance, function ($instance) {
329 return DAO::remove($instance);
330 }, 'deleted', 'Unable to delete the instance', $keyValues);
331 }
332
333 public static function _getApiVersion() {
334 return '?';
335 }
336
342 public static function _getTemplateFile() {
343 return 'restController.tpl';
344 }
345}
Manager for caches (Router, Rest, models).
Base class for controllers.
Starts the framework.
Definition Startup.php:19
static getAction()
Returns tha active action.
Definition Startup.php:318
Abstract base class for Rest controllers.
__construct()
Constructor initialize $view variable.
_delete(... $keyValues)
Delete the instance of $model selected by the primary key $keyValues.
_getOneToMany($ids, $member, $include=false, $useCache=false)
_getAll()
Returns all the instances from the model $resource.
_update(... $keyValues)
Update an instance of $model selected by the primary key $keyValues Require members values in $_POST ...
_getOne($keyValues, $include=false, $useCache=false)
Get the first object corresponding to the $keyValues.
_getManyToMany($ids, $member, $include=false, $useCache=false)
_getManyToOne($ids, $member, $include=false, $useCache=false)
connect()
Realize the connection to the server.
initialize()
Method called before each action Can be override in derived class.
finalize()
Method called after each action Can be override in derived class.
_getRelationShip($id, $member)
Returns an associated member value(s).
checkPermissions($action, $datas=null)
To override in derived classes.
onInvalidControl()
Called if isValid () returns false To be override in sub classes.
_add()
Insert a new instance of $model Require members values in $_POST array.
isValid($action)
Returns True if access to the controller is allowed To be override in sub classes.
static _getTemplateFile()
Returns the template for creating this type of controller.
_get($condition='1=1', $include=false, $useCache=false)
Returns a list of objects from the server.
requireAuth($action)
Returns true if $action require an authentification with token.
Rest events constants.
Gateway class between database and object model.
Definition DAO.php:33
Object/relational mapping utilities.
Definition OrmUtils.php:17
String utilities.
Definition UString.php:15