Test Failed
Push — master ( 696af1...07df9d )
by Jean-Christophe
09:00
created

RestBaseController::_getOne()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 11
ccs 2
cts 2
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 3
crap 2
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.6
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 14
	public function __construct() {
42 14
		if (! \headers_sent ()) {
43 14
			@\set_exception_handler ( array ($this,'_errorHandler' ) );
44 14
			$this->config = Startup::getConfig ();
45 14
			$this->server = $this->_getRestServer ();
46 14
			$this->server->cors ();
47 14
			$this->responseFormatter = $this->_getResponseFormatter ();
48 14
			$this->server->_setContentType ( $this->contentType );
49 14
			$this->restCache = CacheManager::getRestCacheController ( \get_class ( $this ) );
50
		}
51 13
		if (! $this->isValid ( Startup::getAction () ))
52
			$this->onInvalidControl ();
53 13
	}
54
55 1
	public function index() {
56 1
		$routesPath = Router::getRoutesPathByController ( get_class ( $this ) );
57 1
		echo $this->_getResponseFormatter ()->format ( [ "links" => $routesPath ] );
58 1
	}
59
60 13
	public function isValid($action) {
61 13
		if (isset ( $this->restCache ["authorizations"] )) {
62 12
			if (\array_search ( $action, $this->restCache ["authorizations"] ) !== false) {
63 1
				return $this->server->isValid ();
64
			}
65
		}
66 13
		return true;
67
	}
68
	
69
	/**
70
	 * Returns true if $action require an authentification with token
71
	 * @param string $action
72
	 * @return boolean
73
	 */
74
	protected function requireAuth($action) {
75
		if (isset ( $this->restCache ["authorizations"] )) {
76
			return array_search ( $action, $this->restCache ["authorizations"] ) !== false;
77 1
		}
78 1
		return false;
79 1
	}
80
81 7
	public function onInvalidControl() {
82 7
		throw new \Exception ( 'HTTP/1.1 401 Unauthorized, you need an access token for this request', 401 );
83 7
	}
84
85 9
	/**
86 9
	 * Realize the connection to the server
87 9
	 * To override in derived classes to define your own authentication
88 9
	 */
89
	public function connect() {
90
		$resp=$this->server->connect ( $this );
0 ignored issues
show
Unused Code introduced by
The call to Ubiquity\controllers\rest\RestServer::connect() has too many arguments starting with $this. ( Ignorable by Annotation )

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

90
		/** @scrutinizer ignore-call */ 
91
  $resp=$this->server->connect ( $this );

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
91
		echo $this->_format($resp);
92
	}
93
94
	public function initialize() {
95
		$this->connectDb ( $this->config );
96
	}
97
98 1
	public function finalize() {
99 1
		parent::finalize ();
100 1
		$this->server->finalizeTokens ();
101
	}
102
103
	public function _errorHandler($e) {
104
		$code = 500;
105
		if ($e->getCode () !== 0)
106
			$code = $e->getCode ();
107
		$this->_setResponseCode ( $code );
108
		echo $this->_getResponseFormatter ()->formatException ( $e );
109 1
	}
110
111 1
	public function _setResponseCode($value) {
112 1
		\http_response_code ( $value );
113 1
	}
114 1
115 1
	/**
116
	 * Returns a list of objects from the server.
117
	 *
118
	 * @param string $condition the sql Where part
119
	 * @param boolean|string $include if true, loads associate members with associations, if string, example : client.*,commands
120 1
	 * @param boolean $useCache
121
	 */
122
	public function _get($condition = "1=1", $include = false, $useCache = false) {
123
		try {
124
			$condition = $this->getCondition( $condition );
125
			$include = $this->getInclude ( $include );
126
			$useCache = UString::isBooleanTrue ( $useCache );
127
			$datas = DAO::getAll ( $this->model, $condition, $include, null, $useCache );
128
			echo $this->_getResponseFormatter ()->get ( $datas );
129 3
		} catch ( \Exception $e ) {
130 3
			$this->_setResponseCode ( 500 );
131 3
			echo $this->_getResponseFormatter ()->formatException ( $e );
132 3
		}
133 3
	}
134 3
135 3
	/**
136 3
	 * Get the first object corresponding to the $keyValues.
137
	 *
138 1
	 * @param string $keyValues primary key(s) value(s) or condition
139 1
	 * @param boolean|string $include if true, loads associate members with associations, if string, example : client.*,commands
140
	 * @param boolean $useCache if true then response is cached
141 3
	 */
142
	public function _getOne($keyValues, $include = false, $useCache = false) {
143 1
		$keyValues = $this->getCondition( $keyValues );
144 1
		$include = $this->getInclude ( $include );
145
		$useCache = UString::isBooleanTrue ( $useCache );
146
		$data = DAO::getOne ( $this->model, $keyValues, $include, null, $useCache );
147
		if (isset ( $data )) {
148
			$_SESSION ["_restInstance"] = $data;
149
			echo $this->_getResponseFormatter ()->getOne ( $data );
150
		} else {
151
			$this->_setResponseCode ( 404 );
152
			echo $this->_getResponseFormatter ()->format ( RestError::notFound ( $keyValues, "RestController/getOne" )->asArray () );
153
		}
154 1
	}
155
156 1
	public function _format($arrayMessage) {
157 1
		return $this->_getResponseFormatter ()->format ( $arrayMessage );
158 1
	}
159
160
	/**
161
	 *
162
	 * @param string $ids
163
	 * @param string $member
164
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
165
	 * @param boolean $useCache
166
	 */
167
	public function _getManyToOne($ids, $member, $include = false, $useCache = false) {
168 1
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
169
			return DAO::getManyToOne ( $instance, $member, $include, $useCache );
170 1
		}, $member, $include, $useCache, false );
171 1
	}
172 1
173
	/**
174
	 *
175
	 * @param string $ids
176
	 * @param string $member
177
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
178
	 * @param boolean $useCache
179
	 * @throws \Exception
180
	 */
181
	public function _getOneToMany($ids, $member, $include = false, $useCache = false) {
182 1
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
183
			return DAO::getOneToMany ( $instance, $member, $include, $useCache );
184 1
		}, $member, $include, $useCache, true );
185 1
	}
186 1
187
	/**
188
	 *
189
	 * @param string $ids
190
	 * @param string $member
191
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
192
	 * @param boolean $useCache
193
	 * @throws \Exception
194
	 */
195
	public function _getManyToMany($ids, $member, $include = false, $useCache = false) {
196
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
197
			return DAO::getManyToMany ( $instance, $member, $include, null, $useCache );
198
		}, $member, $include, $useCache, true );
199
	}
200
201
	/**
202
	 * Update an instance of $model selected by the primary key $keyValues
203
	 * Require members values in $_POST array
204
	 *
205
	 * @param array $keyValues
206
	 */
207
	public function _update(...$keyValues) {
208
		$instance = DAO::getOne ( $this->model, $keyValues,false );
209
		$this->operate_ ( $instance, function ($instance) {
210
			$datas = $this->getDatas ();
211
			$this->_setValuesToObject ( $instance, $datas );
212
			if ($this->_validateInstance ( $instance, array_keys ( $datas ) )) {
213
				return $this->updateOperation($instance, $datas,true);
214
			}
215
			return null;
216
		}, "updated", "Unable to update the instance", $keyValues );
217
	}
218
219
	/**
220
	 * Insert a new instance of $model
221
	 * Require members values in $_POST array
222
	 */
223
	public function _add() {
224
		$model = $this->model;
225
		$instance = new $model ();
226
		$this->operate_ ( $instance, function ($instance) {
227
			$datas = $this->getDatas ();
228
			$this->_setValuesToObject ( $instance, $datas );
229
			if ($this->_validateInstance ( $instance, $datas )) {
230
				return $this->AddOperation($instance, $datas,true);
231
			}
232
			return null;
233
		}, "inserted", "Unable to insert the instance", [ ] );
234
	}
235 1
236 1
	/**
237
	 * Delete the instance of $model selected by the primary key $keyValues
238
	 *
239
	 * @param array $keyValues
240
	 */
241
	public function _delete(...$keyValues) {
242
		$instance = DAO::getOne ( $this->model, $keyValues,false );
243 1
		$this->operate_ ( $instance, function ($instance) {
244 1
			return DAO::remove ( $instance );
245
		}, "deleted", "Unable to delete the instance", $keyValues );
246
	}
247
248
	public static function _getApiVersion() {
249
		return '?';
250
	}
251
	
252
	/**
253
	 * Returns the template for creating this type of controller
254
	 * @return string
255
	 */
256
	public static function _getTemplateFile(){
257
		return 'restController.tpl';
258
	}
259
}
260