Test Failed
Push — master ( df5a90...e63dff )
by Jean-Christophe
06:33
created

RestBaseController::_getApiVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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