Passed
Push — master ( 9e15fe...1d956f )
by Jean-Christophe
09:32
created

RestBaseController   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 236
Duplicated Lines 0 %

Test Coverage

Coverage 64.49%

Importance

Changes 0
Metric Value
wmc 30
eloc 88
c 0
b 0
f 0
dl 0
loc 236
ccs 69
cts 107
cp 0.6449
rs 10

21 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 7 3
A index() 0 3 1
A __construct() 0 12 3
A requireAuth() 0 5 2
A connect() 0 3 1
A finalize() 0 3 1
A onInvalidControl() 0 2 1
A initialize() 0 1 1
A _getApiVersion() 0 2 1
A _setResponseCode() 0 2 1
A _getOneToMany() 0 4 1
A _format() 0 2 1
A _getTemplateFile() 0 2 1
A _getOne() 0 11 2
A _errorHandler() 0 3 1
A _getManyToMany() 0 4 1
A _get() 0 10 2
A _getManyToOne() 0 4 1
A _update() 0 10 2
A _delete() 0 5 1
A _add() 0 11 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 13
	public function __construct() {
42 13
		if (! \headers_sent ()) {
43 13
			@\set_exception_handler ( array ($this,'_errorHandler' ) );
44 13
			$this->config = Startup::getConfig ();
45 13
			$this->server = $this->_getRestServer ();
46 13
			$this->server->cors ();
47 13
			$this->responseFormatter = $this->_getResponseFormatter ();
48 13
			$this->server->_setContentType ( $this->contentType );
49 13
			$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 3
	public function isValid($action) {
61 3
		if (isset ( $this->restCache ["authorizations"] )) {
62 2
			if (\array_search ( $action, $this->restCache ["authorizations"] ) !== false) {
63 1
				return $this->server->isValid ();
64
			}
65
		}
66 3
		return true;
67
	}
68
69
	/**
70
	 * Returns true if $action require an authentification with token
71
	 *
72
	 * @param string $action
73
	 * @return boolean
74
	 */
75
	protected function requireAuth($action) {
76
		if (isset ( $this->restCache ["authorizations"] )) {
77
			return array_search ( $action, $this->restCache ["authorizations"] ) !== false;
78
		}
79
		return false;
80
	}
81
82
	public function onInvalidControl() {
83
		throw new \Exception ( 'HTTP/1.1 401 Unauthorized, you need an access token for this request', 401 );
84
	}
85
86
	/**
87
	 * Realize the connection to the server
88
	 * To override in derived classes to define your own authentication
89
	 */
90 1
	public function connect() {
91 1
		$resp = $this->server->connect ();
92 1
		echo $this->_format ( $resp );
93 1
	}
94
95 11
	public function initialize() {
96
		// $this->connectDb ( $this->config );//To check
97 11
	}
98
99 13
	public function finalize() {
100 13
		parent::finalize ();
101 13
		$this->server->finalizeTokens ();
102 13
	}
103
104
	public function _errorHandler($e) {
105
		$this->_setResponseCode ( 200 );
106
		echo $this->_getResponseFormatter ()->formatException ( $e );
107
	}
108
109 1
	public function _setResponseCode($value) {
110 1
		\http_response_code ( $value );
111 1
	}
112
113
	/**
114
	 * Returns a list of objects from the server.
115
	 *
116
	 * @param string $condition the sql Where part
117
	 * @param boolean|string $include if true, loads associate members with associations, if string, example : client.*,commands
118
	 * @param boolean $useCache
119
	 */
120 1
	public function _get($condition = "1=1", $include = false, $useCache = false) {
121
		try {
122 1
			$condition = $this->getCondition ( $condition );
123 1
			$include = $this->getInclude ( $include );
124 1
			$useCache = UString::isBooleanTrue ( $useCache );
125 1
			$datas = DAO::getAll ( $this->model, $condition, $include, null, $useCache );
126 1
			echo $this->_getResponseFormatter ()->get ( $datas );
127
		} catch ( \Exception $e ) {
128
			$this->_setResponseCode ( 500 );
129
			echo $this->_getResponseFormatter ()->formatException ( $e );
130
		}
131 1
	}
132
133
	/**
134
	 * Get the first object corresponding to the $keyValues.
135
	 *
136
	 * @param string $keyValues primary key(s) value(s) or condition
137
	 * @param boolean|string $include if true, loads associate members with associations, if string, example : client.*,commands
138
	 * @param boolean $useCache if true then response is cached
139
	 */
140 3
	public function _getOne($keyValues, $include = false, $useCache = false) {
141 3
		$keyValues = $this->getCondition ( $keyValues );
142 3
		$include = $this->getInclude ( $include );
143 3
		$useCache = UString::isBooleanTrue ( $useCache );
144 3
		$data = DAO::getById ( $this->model, $keyValues, $include, $useCache );
145 3
		if (isset ( $data )) {
146 3
			$_SESSION ["_restInstance"] = $data;
147 3
			echo $this->_getResponseFormatter ()->getOne ( $data );
148
		} else {
149 1
			$this->_setResponseCode ( 404 );
150 1
			echo $this->_getResponseFormatter ()->format ( RestError::notFound ( $keyValues, "RestController/getOne" )->asArray () );
151
		}
152 3
	}
153
154 1
	public function _format($arrayMessage) {
155 1
		return $this->_getResponseFormatter ()->format ( $arrayMessage );
156
	}
157
158
	/**
159
	 *
160
	 * @param string $ids
161
	 * @param string $member
162
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
163
	 * @param boolean $useCache
164
	 */
165 1
	public function _getManyToOne($ids, $member, $include = false, $useCache = false) {
166
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
167 1
			return DAO::getManyToOne ( $instance, $member, $include, $useCache );
168 1
		}, $member, $include, $useCache, false );
169 1
	}
170
171
	/**
172
	 *
173
	 * @param string $ids
174
	 * @param string $member
175
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
176
	 * @param boolean $useCache
177
	 * @throws \Exception
178
	 */
179 1
	public function _getOneToMany($ids, $member, $include = false, $useCache = false) {
180
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
181 1
			return DAO::getOneToMany ( $instance, $member, $include, $useCache );
182 1
		}, $member, $include, $useCache, true );
183 1
	}
184
185
	/**
186
	 *
187
	 * @param string $ids
188
	 * @param string $member
189
	 * @param string|boolean $include if true, loads associate members with associations, if string, example : client.*,commands
190
	 * @param boolean $useCache
191
	 * @throws \Exception
192
	 */
193 1
	public function _getManyToMany($ids, $member, $include = false, $useCache = false) {
194
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $include, $useCache) {
195 1
			return DAO::getManyToMany ( $instance, $member, $include, null, $useCache );
196 1
		}, $member, $include, $useCache, true );
197 1
	}
198
199
	/**
200
	 * Update an instance of $model selected by the primary key $keyValues
201
	 * Require members values in $_POST array
202
	 *
203
	 * @param array $keyValues
204
	 */
205
	public function _update(...$keyValues) {
206
		$instance = DAO::getById ( $this->model, $keyValues, false );
207
		$this->operate_ ( $instance, function ($instance) {
208
			$datas = $this->getDatas ();
209
			$this->_setValuesToObject ( $instance, $datas );
210
			if ($this->_validateInstance ( $instance, array_keys ( $datas ) )) {
211
				return $this->updateOperation ( $instance, $datas, true );
212
			}
213
			return null;
214
		}, "updated", "Unable to update the instance", $keyValues );
215
	}
216
217
	/**
218
	 * Insert a new instance of $model
219
	 * Require members values in $_POST array
220
	 */
221
	public function _add() {
222
		$model = $this->model;
223
		$instance = new $model ();
224
		$this->operate_ ( $instance, function ($instance) {
225
			$datas = $this->getDatas ();
226
			$this->_setValuesToObject ( $instance, $datas );
227
			if ($this->_validateInstance ( $instance, $datas )) {
228
				return $this->AddOperation ( $instance, $datas, true );
229
			}
230
			return null;
231
		}, "inserted", "Unable to insert the instance", [ ] );
232
	}
233
234
	/**
235
	 * Delete the instance of $model selected by the primary key $keyValues
236
	 *
237
	 * @param array $keyValues
238
	 */
239
	public function _delete(...$keyValues) {
240
		$instance = DAO::getById ( $this->model, $keyValues, false );
241
		$this->operate_ ( $instance, function ($instance) {
242
			return DAO::remove ( $instance );
243
		}, "deleted", "Unable to delete the instance", $keyValues );
244
	}
245
246 1
	public static function _getApiVersion() {
247 1
		return '?';
248
	}
249
250
	/**
251
	 * Returns the template for creating this type of controller
252
	 *
253
	 * @return string
254
	 */
255 1
	public static function _getTemplateFile() {
256 1
		return 'restController.tpl';
257
	}
258
}
259