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

RestBaseController::index()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Ubiquity\controllers\rest;
4
5
use Ubiquity\cache\CacheManager;
6
use Ubiquity\controllers\Controller;
7
use Ubiquity\controllers\Startup;
8
use Ubiquity\orm\DAO;
9
use Ubiquity\utils\base\UString;
10
use Ubiquity\controllers\Router;
11
12
/**
13
 * Abstract base class for Rest controllers.
14
 * Ubiquity\controllers\rest$RestController
15
 * This class is part of Ubiquity
16
 *
17
 * @author jcheron <[email protected]>
18
 * @version 1.0.5
19
 *
20
 */
21
abstract class RestBaseController extends Controller {
22
	use RestControllerUtilitiesTrait;
23
	protected $config;
24
	protected $model;
25
	protected $contentType;
26
	protected $restCache;
27
	protected $useValidation = true;
28
29
	/**
30
	 *
31
	 * @var ResponseFormatter
32
	 */
33
	protected $responseFormatter;
34
35
	/**
36
	 *
37
	 * @var RestServer
38
	 */
39
	protected $server;
40
41 10
	public function __construct() {
42 10
		if (! \headers_sent ()) {
43 10
			@\set_exception_handler ( array ($this,'_errorHandler' ) );
44 10
			$this->config = Startup::getConfig ();
45 10
			$this->server = $this->_getRestServer ();
46 10
			$this->server->cors ();
47 10
			$this->responseFormatter = $this->_getResponseFormatter ();
48 10
			$this->contentType = "application/json";
49 10
			$this->server->_setContentType ( $this->contentType );
50 10
			$this->restCache = CacheManager::getRestCacheController ( \get_class ( $this ) );
51
		}
52 9
		if (! $this->isValid ( Startup::getAction () ))
53
			$this->onInvalidControl ();
54 9
	}
55
56 1
	public function index() {
57 1
		$routesPath = Router::getRoutesPathByController ( get_class ( $this ) );
58 1
		echo $this->_getResponseFormatter ()->format ( [ "links" => $routesPath ] );
59 1
	}
60
61 9
	public function isValid($action) {
62 9
		if (isset ( $this->restCache ["authorizations"] )) {
63 8
			if (\array_search ( $action, $this->restCache ["authorizations"] ) !== false) {
64 1
				return $this->server->isValid ();
65
			}
66
		}
67 9
		return true;
68
	}
69
70
	public function onInvalidControl() {
71
		throw new \Exception ( 'HTTP/1.1 401 Unauthorized, you need an access token for this request', 401 );
72
	}
73
74
	/**
75
	 * Realize the connection to the server
76
	 * To override in derived classes to define your own authentication
77
	 */
78 1
	public function connect() {
79 1
		$this->server->connect ( $this );
80 1
	}
81
82 7
	public function initialize() {
83 7
		$this->connectDb ( $this->config );
84 7
	}
85
86 9
	public function finalize() {
87 9
		parent::finalize ();
88 9
		$this->server->finalizeTokens ();
89 9
	}
90
91
	public function _errorHandler($e) {
92
		$code = 500;
93
		if ($e->getCode () !== 0)
94
			$code = $e->getCode ();
95
		$this->_setResponseCode ( $code );
96
		echo $this->_getResponseFormatter ()->formatException ( $e );
97
	}
98
99 1
	public function _setResponseCode($value) {
100 1
		\http_response_code ( $value );
101 1
	}
102
103
	/**
104
	 * Returns a list of objects from the server.
105
	 *
106
	 * @param string $condition
107
	 *        	the sql Where part
108
	 * @param boolean|string $include
109
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
110
	 * @param boolean $useCache
111
	 */
112 1
	public function _get($condition = "1=1", $include = false, $useCache = false) {
113
		try {
114 1
			$condition = \urldecode ( $condition );
115 1
			$include = $this->getInclude ( $include );
116 1
			$useCache = UString::isBooleanTrue ( $useCache );
117 1
			$datas = DAO::getAll ( $this->model, $condition, $include, null, $useCache );
118 1
			echo $this->_getResponseFormatter ()->get ( $datas );
119
		} catch ( \Exception $e ) {
120
			$this->_setResponseCode ( 500 );
121
			echo $this->_getResponseFormatter ()->formatException ( $e );
122
		}
123 1
	}
124
125
	/**
126
	 * Get the first object corresponding to the $keyValues.
127
	 *
128
	 * @param string $keyValues
129
	 *        	primary key(s) value(s) or condition
130
	 * @param boolean|string $include
131
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
132
	 * @param boolean $useCache
133
	 *        	if true then response is cached
134
	 */
135 3
	public function _getOne($keyValues, $include = false, $useCache = false) {
136 3
		$keyValues = \urldecode ( $keyValues );
137 3
		$include = $this->getInclude ( $include );
138 3
		$useCache = UString::isBooleanTrue ( $useCache );
139 3
		$data = DAO::getOne ( $this->model, $keyValues, $include, null, $useCache );
140 3
		if (isset ( $data )) {
141 3
			$_SESSION ["_restInstance"] = $data;
142 3
			echo $this->_getResponseFormatter ()->getOne ( $data );
143
		} else {
144 1
			$this->_setResponseCode ( 404 );
145 1
			echo $this->_getResponseFormatter ()->format ( RestError::notFound ( $keyValues, "RestController/getOne" )->asArray () );
146
		}
147 3
	}
148
149 1
	public function _format($arrayMessage) {
150 1
		return $this->_getResponseFormatter ()->format ( $arrayMessage );
151
	}
152
153
	/**
154
	 *
155
	 * @param string $ids
156
	 * @param string $member
157
	 * @param array|boolean $include
158
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
159
	 * @param boolean $useCache
160
	 */
161 1
	public function _getManyToOne($ids, $member, $include = false, $useCache = false) {
162
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
163 1
			return DAO::getManyToOne ( $instance, $member, $include, $useCache );
164 1
		}, $member, $include, $useCache, false );
0 ignored issues
show
Bug introduced by
It seems like $include can also be of type array; however, parameter $include of Ubiquity\controllers\res...sociatedMemberValues_() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

164
		}, $member, /** @scrutinizer ignore-type */ $include, $useCache, false );
Loading history...
165 1
	}
166
167
	/**
168
	 *
169
	 * @param string $ids
170
	 * @param string $member
171
	 * @param array|boolean $include
172
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
173
	 * @param boolean $useCache
174
	 * @throws \Exception
175
	 */
176 1
	public function _getOneToMany($ids, $member, $include = false, $useCache = false) {
177
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
178 1
			return DAO::getOneToMany ( $instance, $member, $include, $useCache );
179 1
		}, $member, $include, $useCache, true );
0 ignored issues
show
Bug introduced by
It seems like $include can also be of type array; however, parameter $include of Ubiquity\controllers\res...sociatedMemberValues_() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

179
		}, $member, /** @scrutinizer ignore-type */ $include, $useCache, true );
Loading history...
180 1
	}
181
182
	/**
183
	 *
184
	 * @param string $ids
185
	 * @param string $member
186
	 * @param array|boolean $include
187
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
188
	 * @param boolean $useCache
189
	 * @throws \Exception
190
	 */
191 1
	public function _getManyToMany($ids, $member, $include = false, $useCache = false) {
192
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
193 1
			return DAO::getManyToMany ( $instance, $member, $include, null, $useCache );
194 1
		}, $member, $include, $useCache, true );
0 ignored issues
show
Bug introduced by
It seems like $include can also be of type array; however, parameter $include of Ubiquity\controllers\res...sociatedMemberValues_() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

194
		}, $member, /** @scrutinizer ignore-type */ $include, $useCache, true );
Loading history...
195 1
	}
196
197
	/**
198
	 * Update an instance of $model selected by the primary key $keyValues
199
	 * Require members values in $_POST array
200
	 *
201
	 * @param array $keyValues
202
	 */
203
	public function _update(...$keyValues) {
204
		$instance = DAO::getOne ( $this->model, $keyValues );
205
		$this->operate_ ( $instance, function ($instance) {
206
			$datas=$this->getDatas ();
207
			$this->_setValuesToObject ( $instance, $datas );
208
			if ($this->validateInstance ( $instance ,array_keys($datas))) {
209
				return DAO::update ( $instance );
210
			}
211
			return null;
212
		}, "updated", "Unable to update the instance", $keyValues );
213
	}
214
215
	/**
216
	 * Insert a new instance of $model
217
	 * Require members values in $_POST array
218
	 */
219
	public function _add() {
220
		$model = $this->model;
221
		$instance = new $model ();
222
		$this->operate_ ( $instance, function ($instance) {
223
			$datas=$this->getDatas ();
224
			$this->_setValuesToObject ( $instance, $datas );
225
			if ($this->validateInstance ( $instance ,$datas)) {
226
				return DAO::insert ( $instance );
227
			}
228
			return null;
229
		}, "inserted", "Unable to insert the instance", [ ] );
230
	}
231
232
	/**
233
	 * Delete the instance of $model selected by the primary key $keyValues
234
	 *
235
	 * @param array $keyValues
236
	 */
237
	public function _delete(...$keyValues) {
238
		$instance = DAO::getOne ( $this->model, $keyValues );
239
		$this->operate_ ( $instance, function ($instance) {
240
			return DAO::remove ( $instance );
241
		}, "deleted", "Unable to delete the instance", $keyValues );
242
	}
243
244 1
	public static function _getApiVersion() {
245 1
		return '?';
246
	}
247
}
248