Passed
Push — master ( 64da0c...c6d718 )
by Jean-Christophe
11:31
created

RestBaseController   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 239
Duplicated Lines 0 %

Test Coverage

Coverage 88.18%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 31
eloc 91
c 1
b 0
f 0
dl 0
loc 239
ccs 97
cts 110
cp 0.8818
rs 9.92

21 Methods

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