Test Failed
Branch master (5614f0)
by Jean-Christophe
07:11
created

RestControllerUtilitiesTrait::addViolation()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 2
ccs 0
cts 1
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Ubiquity\controllers\rest;
4
5
use Ubiquity\orm\DAO;
6
use Ubiquity\utils\base\UString;
7
use Ubiquity\utils\http\URequest;
8
use Ubiquity\contents\validation\ValidatorsManager;
9
use Ubiquity\contents\validation\validators\ConstraintViolation;
10
use Ubiquity\orm\OrmUtils;
11
12
/**
13
 * Rest controller internal utilities.
14
 * Ubiquity\controllers\rest$RestControllerUtilitiesTrait
15
 * This class is part of Ubiquity
16
 *
17
 * @author jcheron <[email protected]>
18
 * @version 1.0.4
19
 * @property ResponseFormatter $responseFormatter
20
 * @property RestServer $server
21
 * @property string $model
22
 *
23
 */
24
trait RestControllerUtilitiesTrait {
25
	protected $errors;
26
27
	abstract public function _setResponseCode($value);
28
29
	protected function getDatas() {
30
		return URequest::getDatas ();
31
	}
32
33
	/**
34
	 *
35
	 * @param string $param
36
	 * @param string|boolean $default
37
	 * @return string|boolean
38
	 */
39
	protected function getRequestParam($param, $default) {
40
		if (isset ( $_GET [$param] )) {
41
			return $_GET [$param];
42
		}
43
		return $default;
44
	}
45
46
	protected function operate_($instance, $callback, $status, $exceptionMessage, $keyValues) {
47
		if (isset ( $instance )) {
48
			$result = $callback ( $instance );
49
			if ($result === true) {
50
				$formatter = $this->_getResponseFormatter ();
51
				echo $formatter->format ( [ "status" => $status,"data" => $formatter->cleanRestObject ( $instance ) ] );
52
			} elseif ($result === null) {
53
				$this->displayErrors ();
54
			} else {
55
				throw new \Exception ( $exceptionMessage );
56
			}
57
		} else {
58
			$this->_setResponseCode ( 404 );
59
			echo $this->_getResponseFormatter ()->format ( [ "message" => "No result found","keyValues" => $keyValues ] );
60
		}
61
	}
62
63
	protected function generatePagination(&$filter, $pageNumber, $pageSize) {
64
		$count = DAO::count ( $this->model, $filter );
65
		$pagesCount = ceil ( $count / $pageSize );
66
		$pages = [ 'self' => $pageNumber,'first' => 1,'last' => $pagesCount,'pageSize' => $pageSize ];
67
		if ($pageNumber - 1 > 0) {
68
			$pages ['prev'] = $pageNumber - 1;
69
		}
70
		if ($pageNumber + 1 <= $pagesCount) {
71
			$pages ['next'] = $pageNumber + 1;
72
		}
73
		$offset = ($pageNumber - 1) * $pageSize;
74
		$filter .= ' limit ' . $offset . ',' . $pageSize;
75
		return $pages;
76
	}
77 14
78 14
	protected function updateOperation($instance, $datas, $updateMany = false) {
79 14
		return DAO::update ( $instance, $updateMany );
80
	}
81 14
82
	protected function AddOperation($instance, $datas, $insertMany = false) {
83
		return DAO::insert ( $instance, $insertMany );
84
	}
85
86
	/**
87
	 *
88
	 * @return \Ubiquity\controllers\rest\ResponseFormatter
89 8
	 */
90 8
	protected function _getResponseFormatter() {
91
		if (! isset ( $this->responseFormatter )) {
92
			$this->responseFormatter = $this->getResponseFormatter ();
93 14
		}
94 14
		return $this->responseFormatter;
95 14
	}
96
97 14
	/**
98
	 * To override, returns the active formatter for the response
99
	 *
100
	 * @return \Ubiquity\controllers\rest\ResponseFormatter
101
	 */
102
	protected function getResponseFormatter(): ResponseFormatter {
103
		return new ResponseFormatter ();
104
	}
105 8
106 8
	protected function _getRestServer() {
107
		if (! isset ( $this->server )) {
108
			$this->server = $this->getRestServer ();
109 7
		}
110 7
		return $this->server;
111 7
	}
112 7
113
	/**
114 7
	 * To override, returns the active RestServer
115
	 *
116
	 * @return \Ubiquity\controllers\rest\RestServer
117
	 */
118
	protected function getRestServer(): RestServer {
119
		return new RestServer ( $this->config );
120
	}
121
122
	protected function connectDb($config) {
123
		$db = $config ["database"];
124
		if ($db ["dbName"] !== "") {
125
			DAO::connect ( $db ["type"], $db ["dbName"], $db ["serverName"] ?? '127.0.0.1', $db ["port"] ?? 3306, $db ["user"] ?? 'root', $db ["password"] ?? '', $db ["options"] ?? [ ], $db ["cache"] ?? false);
126
		}
127
	}
128
129
	/**
130
	 * Updates $instance with $values
131
	 * To eventually be redefined in derived classes
132
	 *
133
	 * @param object $instance the instance to update
134
	 * @param array|null $values
135 6
	 */
136 6
	protected function _setValuesToObject($instance, $values = null) {
137
		if (URequest::isJSON ()) {
138
			$values = \json_decode ( $values, true );
139 6
		}
140
		URequest::setValuesToObject ( $instance, $values );
141
	}
142
143
	/**
144
	 *
145
	 * @param string|boolean $include
146
	 * @return array|boolean
147
	 */
148
	protected function getInclude($include) {
149
		if (! UString::isBooleanStr ( $include )) {
150
			return explode ( ",", $include );
151
		}
152
		return UString::isBooleanTrue ( $include );
153
	}
154
155
	protected function addError($code, $title, $detail = null, $source = null, $status = null) {
156
		$this->errors [] = new RestError ( $code, $title, $detail, $source, $status );
157
	}
158
159
	protected function hasErrors() {
160
		return is_array ( $this->errors ) && sizeof ( $this->errors ) > 0;
161
	}
162
163
	protected function displayErrors() {
164
		if ($this->hasErrors ()) {
165
			$status = 200;
166
			$errors = [ ];
167
			foreach ( $this->errors as $error ) {
168
				$errors [] = $error->asArray ();
169
				if ($error->getStatus () > $status) {
170
					$status = $error->getStatus ();
171
				}
172
			}
173
			echo $this->_getResponseFormatter ()->format ( [ 'errors' => $errors ] );
174
			$this->_setResponseCode ( $status );
175
			return true;
176
		}
177 3
		return false;
178 3
	}
179 3
180 3
	/**
181 3
	 *
182 2
	 * @param string $ids The primary key values (comma separated if pk is multiple)
183
	 * @param callable $getDatas
184 1
	 * @param string $member The member to load
185
	 * @param boolean|string $include if true, loads associate members with associations, if string, example : client.*,commands
186 3
	 * @param boolean $useCache
187
	 * @param boolean $multiple
188
	 * @throws \Exception
189
	 */
190
	protected function getAssociatedMemberValues_($ids, $getDatas, $member, $include = false, $useCache = false, $multiple = true) {
191
		$include = $this->getInclude ( $include );
192
		$useCache = UString::isBooleanTrue ( $useCache );
193
		$datas = $getDatas ( [ $this->model,$ids ], $member, $include, $useCache );
194
		if ($multiple) {
195
			echo $this->_getResponseFormatter ()->get ( $datas );
196
		} else {
197
			echo $this->_getResponseFormatter ()->getOne ( $datas );
198
		}
199
	}
200
201
	public function _validateInstance($instance, $members) {
202
		if ($this->useValidation) {
203
			$isValid = true;
204
			$violations = ValidatorsManager::validate ( $instance );
205
			foreach ( $violations as $violation ) {
206
				if (array_search ( $violation->getMember (), $members ) !== false) {
207
					$this->addViolation ( $violation );
208
					$isValid = false;
209
				}
210
			}
211
			return $isValid;
212
		}
213
		return true;
214
	}
215
216
	protected function addViolation(ConstraintViolation $violation) {
217
		$this->addError ( 406, 'Validation error', $violation->getMessage (), $violation->getMember (), $violation->getValidatorType () );
218
	}
219
220
	protected function getPrimaryKeysFromDatas($datas, $model) {
221
		$pks = OrmUtils::getKeyFields ( $model );
222
		$result = [ ];
223
		foreach ( $pks as $pk ) {
224
			if (isset ( $datas [$pk] )) {
225
				$result [] = $datas [$pk];
226
			} else {
227
				$this->addError ( 404, 'Primary key required', 'The primary key ' . $pk . ' is required!', $pk );
228
			}
229
		}
230
		return $result;
231
	}
232
}
233
234