Passed
Push — master ( b9acc3...1dafdc )
by Jean-Christophe
03:25
created

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