Completed
Push — master ( 506749...99ae87 )
by Jean-Christophe
03:59
created

RestController::_format()   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 1
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\utils\http\URequest;
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.2
19
 *
20
 */
21
abstract class RestController extends Controller {
22
	use RestControllerUtilitiesTrait;
23
	protected $config;
24
	protected $model;
25
	protected $contentType;
26
	protected $restCache;
27
	/**
28
	 *
29
	 * @var ResponseFormatter
30
	 */
31
	protected $responseFormatter;
32
33
	/**
34
	 *
35
	 * @var RestServer
36
	 */
37
	protected $server;
38
39 2
	public function __construct() {
40 2
		if (! \headers_sent ()) {
41 2
			@\set_exception_handler ( array ($this,'_errorHandler' ) );
42 2
			$this->config = Startup::getConfig ();
43 2
			$this->server = new RestServer ( $this->config );
44 2
			$this->server->cors ();
45 2
			$this->responseFormatter = new ResponseFormatter ();
46 2
			$this->contentType = "application/json";
47 2
			$this->server->_setContentType ( $this->contentType );
48 2
			$this->restCache = CacheManager::getRestCacheController ( \get_class ( $this ) );
49
		}
50 2
		if (! $this->isValid ( Startup::getAction () ))
51
			$this->onInvalidControl ();
52 2
	}
53
54 2
	public function isValid($action) {
55 2
		if (isset ( $this->restCache ["authorizations"] )) {
56 2
			if (\array_search ( $action, $this->restCache ["authorizations"] ) !== false) {
57 1
				return $this->server->isValid ();
58
			}
59
		}
60 2
		return true;
61
	}
62
63
	public function onInvalidControl() {
64
		throw new \Exception ( 'HTTP/1.1 401 Unauthorized, you need an access token for this request', 401 );
65
	}
66
67
	/**
68
	 * Realize the connection to the server
69
	 * To override in derived classes to define your own authentication
70
	 */
71 1
	public function connect() {
72 1
		$this->server->connect ( $this );
73 1
	}
74
75 1
	public function initialize() {
76 1
		$thisClass = \get_class ( $this );
77 1
		if (! isset ( $this->model ))
78 1
			$this->model = CacheManager::getRestResource ( $thisClass );
79 1
		if (! isset ( $this->model )) {
80
			$modelsNS = $this->config ["mvcNS"] ["models"];
81
			$this->model = $modelsNS . "\\" . $this->_getResponseFormatter ()->getModel ( $thisClass );
82
		}
83 1
		$this->connectDb ( $this->config );
84 1
	}
85
86 2
	public function finalize() {
87 2
		parent::finalize ();
88 2
		$this->server->finalizeTokens ();
89 2
	}
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 all objects for the resource $model
105
	 *
106
	 * @route("cache"=>false,"priority"=>100)
107
	 */
108 1
	public function index() {
109 1
		$datas = DAO::getAll ( $this->model );
110 1
		echo $this->_getResponseFormatter ()->get ( $datas );
111 1
	}
112
113
	/**
114
	 * Default route for requiring a single object
115
	 *
116
	 * @route("{id}","methods"=>["get","options"],"requirements"=>["id"=>"[0-9]+"])
117
	 */
118 1
	public function getById($id) {
119 1
		$this->getOne ( $id, true, false );
120 1
	}
121
122
	/**
123
	 * Returns a list of objects from the server
124
	 *
125
	 * @param string $condition
126
	 *        	the sql Where part
127
	 * @param boolean|string $included
128
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
129
	 * @param boolean $useCache
130
	 */
131 1
	public function get($condition = "1=1", $included = false, $useCache = false) {
132
		try {
133 1
			$condition = \urldecode ( $condition );
134 1
			$included = $this->getIncluded ( $included );
135 1
			$useCache = UString::isBooleanTrue ( $useCache );
136 1
			$datas = DAO::getAll ( $this->model, $condition, $included, null, $useCache );
137 1
			echo $this->_getResponseFormatter ()->get ( $datas );
138
		} catch ( \Exception $e ) {
139
			$this->_setResponseCode ( 500 );
140
			echo $this->_getResponseFormatter ()->formatException ( $e );
141
		}
142 1
	}
143
144
	/**
145
	 * Get the first object corresponding to the $keyValues
146
	 *
147
	 * @param string $keyValues
148
	 *        	primary key(s) value(s) or condition
149
	 * @param boolean|string $included
150
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
151
	 * @param boolean $useCache
152
	 *        	if true then response is cached
153
	 */
154 1
	public function getOne($keyValues, $included = false, $useCache = false) {
155 1
		$keyValues = \urldecode ( $keyValues );
156 1
		$included = $this->getIncluded ( $included );
157 1
		$useCache = UString::isBooleanTrue ( $useCache );
158 1
		$data = DAO::getOne ( $this->model, $keyValues, $included, null, $useCache );
159 1
		if (isset ( $data )) {
160 1
			$_SESSION ["_restInstance"] = $data;
161 1
			echo $this->_getResponseFormatter ()->getOne ( $data );
162
		} else {
163 1
			$this->_setResponseCode ( 404 );
164 1
			echo $this->_getResponseFormatter ()->format ( [ "message" => "No result found","keyValues" => $keyValues ] );
165
		}
166 1
	}
167
168 1
	public function _format($arrayMessage) {
169 1
		return $this->_getResponseFormatter ()->format ( $arrayMessage );
170
	}
171
172
	/**
173
	 *
174
	 * @param string $member
175
	 * @param boolean|string $included
176
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
177
	 * @param boolean $useCache
178
	 * @throws \Exception
179
	 */
180
	public function getOneToMany($member, $included = false, $useCache = false) {
181
		$this->getMany_ ( function ($instance, $member, $included, $useCache) {
182
			return DAO::getOneToMany ( $instance, $member, $included, $useCache );
183
		}, $member, $included, $useCache );
184
	}
185
186
	/**
187
	 *
188
	 * @param string $member
189
	 * @param boolean|string $included
190
	 *        	if true, loads associate members with associations, if string, example : client.*,commands
191
	 * @param boolean $useCache
192
	 * @throws \Exception
193
	 */
194
	public function getManyToMany($member, $included = false, $useCache = false) {
195
		$this->getMany_ ( function ($instance, $member, $included, $useCache) {
196
			return DAO::getManyToMany ( $instance, $member, $included, null, $useCache );
197
		}, $member, $included, $useCache );
198
	}
199
200
	/**
201
	 * Update an instance of $model selected by the primary key $keyValues
202
	 * Require members values in $_POST array
203
	 *
204
	 * @param array $keyValues
205
	 * @authorization
206
	 */
207
	public function update(...$keyValues) {
208
		$instance = DAO::getOne ( $this->model, $keyValues );
209
		$this->operate_ ( $instance, function ($instance) {
210
			$this->_setValuesToObject ( $instance, URequest::getDatas () );
211
			return DAO::update ( $instance );
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
	 * @authorization
220
	 */
221
	public function add() {
222
		$model = $this->model;
223
		$instance = new $model ();
224
		$this->operate_ ( $instance, function ($instance) {
225
			$this->_setValuesToObject ( $instance, URequest::getDatas () );
226
			return DAO::insert ( $instance );
227
		}, "inserted", "Unable to insert the instance", [ ] );
228
	}
229
230
	/**
231
	 * Delete the instance of $model selected by the primary key $keyValues
232
	 * Requires an authorization with access token
233
	 *
234
	 * @param array $keyValues
235
	 * @route("methods"=>["delete"],"priority"=>30)
236
	 * @authorization
237
	 */
238
	public function delete(...$keyValues) {
239
		$instance = DAO::getOne ( $this->model, $keyValues );
240
		$this->operate_ ( $instance, function ($instance) {
241
			return DAO::remove ( $instance );
242
		}, "deleted", "Unable to delete the instance", $keyValues );
243
	}
244
}
245