Passed
Push — master ( 3b562b...c53b79 )
by Jean-Christophe
05:56
created

RestControllerUtilitiesTrait::getIncluded()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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