Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
RestControllerUtilitiesTrait.php
Go to the documentation of this file.
1<?php
2
4
16
31 protected $errors;
32
33 abstract public function _setResponseCode($value);
34
35 protected function getDatas() {
36 return $this->_getRequestFormatter ()->getDatas ( $this->model );
37 }
38
45 protected function getRequestParam($param, $default) {
46 return $_GET [$param] ?? $default;
47 }
48
49 protected function operate_($instance, $callback, $status, $exceptionMessage, $keyValues) {
50 if (isset ( $instance )) {
51 $result = $callback ( $instance );
52 if ($result == true) {
53 $formatter = $this->_getResponseFormatter ();
54 echo $formatter->format ( [ "status" => $status,"data" => $formatter->cleanRestObject ( $instance ) ] );
55 } elseif ($result === null) {
56 $this->displayErrors ();
57 } else {
58 throw new \Exception ( $exceptionMessage );
59 }
60 } else {
61 $this->_setResponseCode ( 404 );
62 echo $this->_getResponseFormatter ()->format ( [ "message" => "No result found","keyValues" => $keyValues ] );
63 }
64 }
65
66 protected function generatePagination(&$filter, $pageNumber, $pageSize) {
67 $count = DAO::count ( $this->model, $filter );
68 $pagesCount = \ceil ( $count / $pageSize );
69 $pages = [ 'self' => $pageNumber,'first' => 1,'last' => $pagesCount,'pageSize' => $pageSize ];
70 if ($pageNumber - 1 > 0) {
71 $pages ['prev'] = $pageNumber - 1;
72 }
73 if ($pageNumber + 1 <= $pagesCount) {
74 $pages ['next'] = $pageNumber + 1;
75 }
76 $offset = ($pageNumber - 1) * $pageSize;
77 $filter .= ' limit ' . $offset . ',' . $pageSize;
78 return $pages;
79 }
80
81 protected function updateOperation($instance, $datas, $updateMany = false) {
82 return DAO::update ( $instance, $updateMany );
83 }
84
85 protected function addOperation($instance, $datas, $insertMany = false) {
86 return DAO::insert ( $instance, $insertMany );
87 }
88
93 protected function _getResponseFormatter() {
94 if (! isset ( $this->responseFormatter )) {
95 $this->responseFormatter = $this->getResponseFormatter ();
96 }
97 return $this->responseFormatter;
98 }
99
106 return new ResponseFormatter ();
107 }
108
113 protected function _getRequestFormatter() {
114 if (! isset ( $this->requestFormatter )) {
115 $this->requestFormatter = $this->getRequestFormatter ();
116 }
117 return $this->requestFormatter;
118 }
119
125 protected function getRequestFormatter(): RequestFormatter {
126 return new RequestFormatter ();
127 }
128
129 protected function _getRestServer() {
130 if (! isset ( $this->server )) {
131 $this->server = $this->getRestServer ();
132 }
133 return $this->server;
134 }
135
141 protected function getRestServer(): RestServer {
142 return new RestServer ( $this->config );
143 }
144
153 protected function _setValuesToObject($instance, $values = [ ]) {
154 if (URequest::isJSON ()) {
155 if (\is_string ( $values )) {
156 $values = \json_decode ( $values, true );
157 }
158 }
159 $className = \get_class ( $instance );
160 $fieldsInRelationForUpdate = OrmUtils::getFieldsInRelationsForUpdate_ ( $className );
161 $manyToOneRelations = $fieldsInRelationForUpdate ["manyToOne"];
162
163 $members = \array_keys ( $values );
164 OrmUtils::setFieldToMemberNames ( $members, $fieldsInRelationForUpdate ["relations"] );
165 URequest::setValuesToObject ( $instance, $values );
166 if ($manyToOneRelations) {
167 $this->updateManyToOne ( $manyToOneRelations, $members, $className, $instance, $values );
168 }
169 }
170
171 protected function updateManyToOne($manyToOneRelations, $members, $className, $instance, $values) {
172 foreach ( $manyToOneRelations as $member ) {
173 if (\array_search ( $member, $members ) !== false) {
174 $joinColumn = OrmUtils::getAnnotationInfoMember ( $className, "#joinColumn", $member );
175 if ($joinColumn) {
176 $fkClass = $joinColumn ["className"];
177 $fkField = $joinColumn ["name"];
178 if (isset ( $values [$fkField] )) {
179 $fkObject = DAO::getById ( $fkClass, $values ["$fkField"] );
180 Reflexion::setMemberValue ( $instance, $member, $fkObject );
181 }
182 }
183 }
184 }
185 }
186
192 protected function getInclude($include) {
193 if (! UString::isBooleanStr ( $include )) {
194 return \explode ( ',', $include );
195 }
196 return UString::isBooleanTrue ( $include );
197 }
198
199 protected function addError($code, $title, $detail = null, $source = null, $status = null) {
200 $this->errors [] = new RestError( $code, $title, $detail, $source, $status );
201 }
202
203 protected function hasErrors() {
204 return \is_array ( $this->errors ) && \count ( $this->errors ) > 0;
205 }
206
207 protected function displayErrors() {
208 if ($this->hasErrors ()) {
209 $status = 200;
210 $errors = [ ];
211 foreach ( $this->errors as $error ) {
212 $errors [] = $error->asArray ();
213 if ($error->getStatus () > $status) {
214 $status = $error->getStatus ();
215 }
216 }
217 echo $this->_getResponseFormatter ()->format ( [ 'errors' => $errors ] );
218 $this->_setResponseCode ( $status );
219 return true;
220 }
221 return false;
222 }
223
234 protected function getAssociatedMemberValues_($ids, $getDatas, $member, $include = false, $useCache = false, $multiple = true) {
235 $include = $this->getInclude ( $include );
236 $useCache = UString::isBooleanTrue ( $useCache );
237 $datas = $getDatas ( [ $this->model,$ids ], $member, $include, $useCache );
238 if ($multiple) {
239 echo $this->_getResponseFormatter ()->get ( $datas );
240 } else {
241 echo $this->_getResponseFormatter ()->getOne ( $datas );
242 }
243 }
244
245 public function _validateInstance($instance, $members, $excludedValidators = [ ]) {
246 if ($this->useValidation) {
247 $isValid = true;
248 $violations = ValidatorsManager::validate ( $instance, '', $excludedValidators );
249 foreach ( $violations as $violation ) {
250 if (\array_search ( $violation->getMember (), $members ) !== false) {
251 $this->addViolation ( $violation );
252 $isValid = false;
253 }
254 }
255 return $isValid;
256 }
257 return true;
258 }
259
260 protected function addViolation(ConstraintViolation $violation) {
261 $this->addError ( 406, 'Validation error', $violation->getMessage (), $violation->getMember (), $violation->getValidatorType () );
262 }
263
264 protected function getPrimaryKeysFromDatas($datas, $model) {
265 $pks = OrmUtils::getKeyFields ( $model );
266 $result = [ ];
267 foreach ( $pks as $pk ) {
268 if (isset ( $datas [$pk] )) {
269 $result [] = $datas [$pk];
270 } else {
271 $this->addError ( 404, 'Primary key required', 'The primary key ' . $pk . ' is required!', $pk );
272 }
273 }
274 return $result;
275 }
276
277 protected function getCondition($condition) {
278 if (\is_array ( $condition )) {
279 $conds = [ ];
280 foreach ( $condition as $f => $v ) {
281 $conds [] = $f . "='" . \urldecode ( $v ) . "'";
282 }
283 $condition = \implode ( ' AND ', $conds );
284 } else {
285 $condition = \urldecode ( $condition );
286 }
287 if (\strpos ( $condition, 'like' ) !== false) {
288 $condition = \str_replace ( '*', '%', $condition );
289 }
290 return $condition;
291 }
292}
293
Constraint Violation Generated During Validation with the ValidatorsManager.
Ubiquity\controllers\rest\formatters$RequestFormatter This class is part of Ubiquity.
updateManyToOne($manyToOneRelations, $members, $className, $instance, $values)
getResponseFormatter()
To override, returns the active formatter for the response.
_setValuesToObject($instance, $values=[])
Updates $instance with $values To eventually be redefined in derived classes.
operate_($instance, $callback, $status, $exceptionMessage, $keyValues)
getAssociatedMemberValues_($ids, $getDatas, $member, $include=false, $useCache=false, $multiple=true)
addError($code, $title, $detail=null, $source=null, $status=null)
getRequestFormatter()
To override, returns the active formatter for the request.
Gateway class between database and object model.
Definition DAO.php:33
Object/relational mapping utilities.
Definition OrmUtils.php:17
Reflection utilities in dev environment only.
Definition Reflexion.php:17
String utilities.
Definition UString.php:15
Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
Definition URequest.php:18