Passed
Push — master ( 55710c...55bc39 )
by Jean-Christophe
06:21
created

RestBaseController::_getManyToMany()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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