Test Failed
Push — master ( bbba5c...a9a47f )
by Jean-Christophe
06:55
created

RestBaseController::_getTemplateFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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