Passed
Push — master ( 8c2233...f2064a )
by Jean-Christophe
05:47
created

RestControllerUtilitiesTrait::getDatas()   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 2
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
9
/**
10
 * Rest controller internal utilities.
11
 * Ubiquity\controllers\rest$RestControllerUtilitiesTrait
12
 * This class is part of Ubiquity
13
 *
14
 * @author jcheron <[email protected]>
15
 * @version 1.0.0
16
 * @property ResponseFormatter $responseFormatter
17
 * @property RestServer $server
18
 *
19
 */
20
trait RestControllerUtilitiesTrait {
21
22
	abstract public function _setResponseCode($value);
23
24
	protected function getDatas() {
25
		return URequest::getDatas ();
26
	}
27
28
	protected function operate_($instance, $callback, $status, $exceptionMessage, $keyValues) {
29
		if (isset ( $instance )) {
30
			$result = $callback ( $instance );
31
			if ($result) {
32
				$formatter = $this->_getResponseFormatter ();
33
				echo $formatter->format ( [ "status" => $status,"data" => $formatter->cleanRestObject ( $instance ) ] );
34
			} else {
35
				throw new \Exception ( $exceptionMessage );
36
			}
37
		} else {
38
			$this->_setResponseCode ( 404 );
39
			echo $this->_getResponseFormatter ()->format ( [ "message" => "No result found","keyValues" => $keyValues ] );
40
		}
41
	}
42
43
	protected function generatePagination(&$filter, $pageNumber, $pageSize) {
44
		$count = DAO::count ( $this->model, $filter );
45
		$pagesCount = ceil ( $count / $pageSize );
46
		$pages = [ 'self' => $pageNumber,'first' => 1,'last' => $pagesCount,'pageSize' => $pageSize ];
47
		if ($pageNumber - 1 > 0) {
48
			$pages ['prev'] = $pageNumber - 1;
49
		}
50
		if ($pageNumber + 1 <= $pagesCount) {
51
			$pages ['next'] = $pageNumber + 1;
52
		}
53
		$offset = ($pageNumber - 1) * $pageSize;
54
		$filter .= ' limit ' . $offset . ',' . $pageSize;
55
		return $pages;
56
	}
57
58 5
	protected function _getResponseFormatter() {
59 5
		if (! isset ( $this->responseFormatter )) {
60 5
			$this->responseFormatter = $this->getResponseFormatter ();
61
		}
62 5
		return $this->responseFormatter;
63
	}
64
65
	/**
66
	 * To override, returns the active formatter for the response
67
	 *
68
	 * @return \Ubiquity\controllers\rest\ResponseFormatter
69
	 */
70 4
	protected function getResponseFormatter(): ResponseFormatter {
71 4
		return new ResponseFormatter ();
72
	}
73
74 5
	protected function _getRestServer() {
75 5
		if (! isset ( $this->server )) {
76 5
			$this->server = $this->getRestServer ();
77
		}
78 5
		return $this->server;
79
	}
80
81
	/**
82
	 * To override, returns the active RestServer
83
	 *
84
	 * @return \Ubiquity\controllers\rest\RestServer
85
	 */
86 5
	protected function getRestServer(): RestServer {
87 5
		return new RestServer ( $this->config );
88
	}
89
90 2
	protected function connectDb($config) {
91 2
		$db = $config ["database"];
92 2
		if ($db ["dbName"] !== "") {
93 2
			DAO::connect ( $db ["type"], $db ["dbName"], @$db ["serverName"], @$db ["port"], @$db ["user"], @$db ["password"], @$db ["options"], @$db ["cache"] );
94
		}
95 2
	}
96
97
	/**
98
	 * Updates $instance with $values
99
	 * To eventually be redefined in derived classes
100
	 *
101
	 * @param object $instance
102
	 *        	the instance to update
103
	 * @param array|null $values
104
	 */
105
	protected function _setValuesToObject($instance, $values = null) {
106
		if (URequest::isJSON ()) {
107
			$values = \json_decode ( $values, true );
108
		}
109
		URequest::setValuesToObject ( $instance, $values );
110
	}
111
112
	/**
113
	 *
114
	 * @param string|boolean $included
115
	 * @return array|boolean
116
	 */
117 2
	protected function getIncluded($included) {
118 2
		if (! UString::isBooleanStr ( $included )) {
119
			return explode ( ",", $included );
120
		}
121 2
		return UString::isBooleanTrue ( $included );
122
	}
123
124
	protected function addError($code, $title, $detail = null, $source = null, $status = null) {
125
		$this->errors [] = new RestError ( $code, $title, $detail, $source, $status );
0 ignored issues
show
Bug Best Practice introduced by
The property errors does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
126
	}
127
128
	protected function hasErrors() {
129
		return is_array ( $this->errors ) && sizeof ( $this->errors ) > 0;
130
	}
131
132
	protected function displayErrors() {
133
		if ($this->hasErrors ()) {
134
			$status = 200;
135
			$errors = [ ];
136
			foreach ( $this->errors as $error ) {
137
				$errors [] = $error->asArray ();
138
				if ($error->getStatus () > $status) {
139
					$status = $error->getStatus ();
140
				}
141
			}
142
			echo $this->_getResponseFormatter ()->format ( [ 'errors' => $errors ] );
143
			$this->_setResponseCode ( $status );
144
			return true;
145
		}
146
		return false;
147
	}
148
149
	/**
150
	 *
151
	 * @param callable $getDatas
152
	 * @param string $member
153
	 * @param boolean|string $included
154
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
155
	 * @param boolean $useCache
156
	 * @throws \Exception
157
	 */
158
	protected function getMany_($getDatas, $member, $included = false, $useCache = false) {
159
		if (isset ( $_SESSION ["_restInstance"] )) {
160
			$included = $this->getIncluded ( $included );
161
			$useCache = UString::isBooleanTrue ( $useCache );
162
			$datas = $getDatas ( $_SESSION ["_restInstance"], $member, $included, $useCache );
163
			echo $this->_getResponseFormatter ()->get ( $datas );
164
		} else {
165
			throw new \Exception ( "You have to call getOne before calling getManyToMany or getOneToMany." );
166
		}
167
	}
168
}
169
170