Test Failed
Push — master ( 7df265...08d2f1 )
by Jean-Christophe
06:27
created

RestControllerUtilitiesTrait::getRestServer()   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 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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.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
				echo $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 5
		}
60 5
		$offset = ($pageNumber - 1) * $pageSize;
61 5
		$filter .= ' limit ' . $offset . ',' . $pageSize;
62
		return $pages;
63 5
	}
64
65
	/**
66
	 *
67
	 * @return \Ubiquity\controllers\rest\ResponseFormatter
68
	 */
69
	protected function _getResponseFormatter() {
70
		if (! isset ( $this->responseFormatter )) {
71 4
			$this->responseFormatter = $this->getResponseFormatter ();
72 4
		}
73
		return $this->responseFormatter;
74
	}
75 5
76 5
	/**
77 5
	 * To override, returns the active formatter for the response
78
	 *
79 5
	 * @return \Ubiquity\controllers\rest\ResponseFormatter
80
	 */
81
	protected function getResponseFormatter(): ResponseFormatter {
82
		return new ResponseFormatter ();
83
	}
84
85
	protected function _getRestServer() {
86
		if (! isset ( $this->server )) {
87 5
			$this->server = $this->getRestServer ();
88 5
		}
89
		return $this->server;
90
	}
91 2
92 2
	/**
93 2
	 * To override, returns the active RestServer
94 2
	 *
95
	 * @return \Ubiquity\controllers\rest\RestServer
96 2
	 */
97
	protected function getRestServer(): RestServer {
98
		return new RestServer ( $this->config );
99
	}
100
101
	protected function connectDb($config) {
102
		$db = $config ["database"];
103
		if ($db ["dbName"] !== "") {
104
			DAO::connect ( $db ["type"], $db ["dbName"], @$db ["serverName"], @$db ["port"], @$db ["user"], @$db ["password"], @$db ["options"], @$db ["cache"] );
105
		}
106
	}
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 2
			$values = \json_decode ( $values, true );
119 2
		}
120
		URequest::setValuesToObject ( $instance, $values );
121
	}
122 2
123
	/**
124
	 *
125
	 * @param string|boolean $included
126
	 * @return array|boolean
127
	 */
128
	protected function getIncluded($included) {
129
		if (! UString::isBooleanStr ( $included )) {
130
			return explode ( ",", $included );
131
		}
132
		return UString::isBooleanTrue ( $included );
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 $included
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
	protected function getAssociatedMemberValues_($ids, $getDatas, $member, $included = false, $useCache = false, $multiple = true) {
174
		$included = $this->getIncluded ( $included );
175
		$useCache = UString::isBooleanTrue ( $useCache );
176
		$datas = $getDatas ( [ $this->model,$ids ], $member, $included, $useCache );
177
		if ($multiple) {
178
			echo $this->_getResponseFormatter ()->get ( $datas );
179
		} else {
180
			echo $this->_getResponseFormatter ()->getOne ( $datas );
181
		}
182
	}
183
184
	protected function validateInstance($instance) {
185
		if ($this->useValidation) {
186
			$violations = ValidatorsManager::validate ( $instance );
187
			foreach ( $violations as $violation ) {
188
				$this->addViolation ( $violation );
189
			}
190
			return sizeof ( $violations ) === 0;
191
		}
192
		return true;
193
	}
194
195
	protected function addViolation(ConstraintViolation $violation) {
196
		$this->addError ( 406, 'Validation error', $violation->getMessage (), $violation->getMember (), $violation->getValidatorType () );
197
	}
198
199
	protected function getPrimaryKeysFromDatas($datas, $model) {
200
		$pks = OrmUtils::getKeyFields ( $model );
201
		$result = [ ];
202
		foreach ( $pks as $pk ) {
203
			if (isset ( $datas [$pk] )) {
204
				$result [$pk] = $datas [$pk];
205
			} else {
206
				$this->addError ( 404, 'Primary key required', 'The primary key ' . $pk . ' is required!', $pk );
207
			}
208
		}
209
		return $result;
210
	}
211
}
212
213