Test Failed
Push — master ( 7df265...08d2f1 )
by Jean-Christophe
06:27
created

RestBaseController::initialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 2
ccs 2
cts 2
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.4
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 5
	protected $server;
40 5
41 5
	public function __construct() {
42 5
		if (! \headers_sent ()) {
43 5
			@\set_exception_handler ( array ($this,'_errorHandler' ) );
44 5
			$this->config = Startup::getConfig ();
45 5
			$this->server = $this->_getRestServer ();
46 5
			$this->server->cors ();
47 5
			$this->responseFormatter = $this->_getResponseFormatter ();
48 5
			$this->contentType = "application/json";
49
			$this->server->_setContentType ( $this->contentType );
50 4
			$this->restCache = CacheManager::getRestCacheController ( \get_class ( $this ) );
51
		}
52 4
		if (! $this->isValid ( Startup::getAction () ))
53
			$this->onInvalidControl ();
54
	}
55
56
	public function index() {
57 4
		$routesPath = Router::getRoutesPathByController ( get_class ( $this ) );
58 4
		echo $this->_getResponseFormatter ()->format ( [ "links" => $routesPath ] );
59 3
	}
60 1
61
	public function isValid($action) {
62
		if (isset ( $this->restCache ["authorizations"] )) {
63 4
			if (\array_search ( $action, $this->restCache ["authorizations"] ) !== false) {
64
				return $this->server->isValid ();
65
			}
66
		}
67
		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 1
	/**
75 1
	 * Realize the connection to the server
76 1
	 * To override in derived classes to define your own authentication
77
	 */
78 2
	public function connect() {
79 2
		$this->server->connect ( $this );
80 2
	}
81
82 4
	public function initialize() {
83 4
		$this->connectDb ( $this->config );
84 4
	}
85 4
86
	public function finalize() {
87
		parent::finalize ();
88
		$this->server->finalizeTokens ();
89
	}
90
91
	public function _errorHandler($e) {
92
		$code = 500;
93
		if ($e->getCode () !== 0)
94
			$code = $e->getCode ();
95 1
		$this->_setResponseCode ( $code );
96 1
		echo $this->_getResponseFormatter ()->formatException ( $e );
97 1
	}
98
99
	public function _setResponseCode($value) {
100
		\http_response_code ( $value );
101
	}
102
103
	/**
104
	 * Returns a list of objects from the server.
105
	 *
106
	 * @param string $condition
107
	 *        	the sql Where part
108 1
	 * @param boolean|string $included
109
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
110 1
	 * @param boolean $useCache
111 1
	 */
112 1
	public function _get($condition = "1=1", $included = false, $useCache = false) {
113 1
		try {
114 1
			$condition = \urldecode ( $condition );
115
			$included = $this->getIncluded ( $included );
116
			$useCache = UString::isBooleanTrue ( $useCache );
117
			$datas = DAO::getAll ( $this->model, $condition, $included, null, $useCache );
118
			echo $this->_getResponseFormatter ()->get ( $datas );
119 1
		} catch ( \Exception $e ) {
120
			$this->_setResponseCode ( 500 );
121
			echo $this->_getResponseFormatter ()->formatException ( $e );
122
		}
123
	}
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 $included
131 2
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
132 2
	 * @param boolean $useCache
133 2
	 *        	if true then response is cached
134 2
	 */
135 2
	public function _getOne($keyValues, $included = false, $useCache = false) {
136 2
		$keyValues = \urldecode ( $keyValues );
137 2
		$included = $this->getIncluded ( $included );
138 2
		$useCache = UString::isBooleanTrue ( $useCache );
139
		$data = DAO::getOne ( $this->model, $keyValues, $included, null, $useCache );
140 1
		if (isset ( $data )) {
141 1
			$_SESSION ["_restInstance"] = $data;
142
			echo $this->_getResponseFormatter ()->getOne ( $data );
143 2
		} else {
144
			$this->_setResponseCode ( 404 );
145 1
			echo $this->_getResponseFormatter ()->format ( RestError::notFound ( $keyValues, "RestController/getOne" )->asArray () );
146 1
		}
147
	}
148
149
	public function _format($arrayMessage) {
150
		return $this->_getResponseFormatter ()->format ( $arrayMessage );
151
	}
152
153
	/**
154
	 *
155
	 * @param string $ids
156
	 * @param string $member
157
	 * @param
158
	 *        	boolean boolean|string $included
159
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
160
	 * @param boolean $useCache
161
	 */
162
	public function _getManyToOne($ids, $member, $included = false, $useCache = false) {
163
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $included, $useCache) {
164
			return DAO::getManyToOne ( $instance, $member, $included, $useCache );
165
		}, $member, $included, $useCache, false );
166
	}
167
168
	/**
169
	 *
170
	 * @param string $ids
171
	 * @param string $member
172
	 * @param boolean|string $included
173
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
174
	 * @param boolean $useCache
175
	 * @throws \Exception
176
	 */
177
	public function _getOneToMany($ids, $member, $included = false, $useCache = false) {
178
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $included, $useCache) {
179
			return DAO::getOneToMany ( $instance, $member, $included, $useCache );
180
		}, $member, $included, $useCache, true );
181
	}
182
183
	/**
184
	 *
185
	 * @param string $ids
186
	 * @param string $member
187
	 * @param boolean|string $included
188
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
189
	 * @param boolean $useCache
190
	 * @throws \Exception
191
	 */
192
	public function _getManyToMany($ids, $member, $included = false, $useCache = false) {
193
		$this->getAssociatedMemberValues_ ( $ids, function ($instance, $member, $included, $useCache) {
194
			return DAO::getManyToMany ( $instance, $member, $included, null, $useCache );
195
		}, $member, $included, $useCache, true );
196
	}
197
198
	/**
199
	 * Update an instance of $model selected by the primary key $keyValues
200
	 * Require members values in $_POST array
201
	 *
202
	 * @param array $keyValues
203
	 * @authorization
204
	 */
205
	public function update(...$keyValues) {
206
		$instance = DAO::getOne ( $this->model, $keyValues );
207
		$this->operate_ ( $instance, function ($instance) {
208
			$this->_setValuesToObject ( $instance, $this->getDatas () );
209
			if ($this->validateInstance ( $instance )) {
210
				return DAO::update ( $instance );
211
			}
212
			return null;
213
		}, "updated", "Unable to update the instance", $keyValues );
214
	}
215
216
	/**
217
	 * Insert a new instance of $model
218
	 * Require members values in $_POST array
219
	 *
220
	 * @authorization
221
	 */
222 1
	public function add() {
223 1
		$model = $this->model;
224
		$instance = new $model ();
225
		$this->operate_ ( $instance, function ($instance) {
226
			$this->_setValuesToObject ( $instance, $this->getDatas () );
227
			if ($this->validateInstance ( $instance )) {
228
				return DAO::insert ( $instance );
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
	 * Requires an authorization with access token
237
	 *
238
	 * @param array $keyValues
239
	 * @route("methods"=>["delete"],"priority"=>30)
240
	 * @authorization
241
	 */
242
	public function delete(...$keyValues) {
243
		$instance = DAO::getOne ( $this->model, $keyValues );
244
		$this->operate_ ( $instance, function ($instance) {
245
			return DAO::remove ( $instance );
246
		}, "deleted", "Unable to delete the instance", $keyValues );
247
	}
248
249
	public static function _getApiVersion() {
250
		return '?';
251
	}
252
}
253