Test Failed
Push — master ( 7df265...08d2f1 )
by Jean-Christophe
06:27
created

JsonApiRestController::delete_()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Ubiquity\controllers\rest\api\jsonapi;
4
5
use Ubiquity\orm\DAO;
6
use Ubiquity\controllers\rest\RestError;
7
use Ubiquity\controllers\Startup;
8
use Ubiquity\controllers\rest\RestBaseController;
9
use Ubiquity\utils\http\URequest;
10
use Ubiquity\orm\OrmUtils;
11
12
/**
13
 * Rest JsonAPI implementation.
14
 * Ubiquity\controllers\rest\api\jsonapi$JsonApiRestController
15
 * This class is part of Ubiquity
16
 *
17
 * @author jcheron <[email protected]>
18
 * @version 1.1.0
19
 * @since Ubiquity 2.0.11
20
 *
21
 */
22
abstract class JsonApiRestController extends RestBaseController {
23
	const API_VERSION = 'JsonAPI 1.0';
24
25 1
	protected function _setResource($resource) {
26 1
		$modelsNS = $this->config ["mvcNS"] ["models"];
27 1
		$this->model = $modelsNS . "\\" . ucfirst ( $resource );
28 1
	}
29
30 1
	protected function _checkResource($resource, $callback) {
31 1
		$this->_setResource ( $resource );
32 1
		if (class_exists ( $this->model )) {
33 1
			$callback ();
34
		} else {
35
			$error = new RestError ( 404, "Not existing class", $this->model . " class does not exists!", Startup::getController () . "/" . Startup::getAction () );
36
			echo $this->_format ( $error->asArray () );
37
		}
38 1
	}
39
40 1
	protected function getRequestParam($param, $default) {
41 1
		if (isset ( $_GET [$param] )) {
42
			return $_GET [$param];
43
		}
44 1
		return $default;
45
	}
46
47
	protected function getDatas() {
48
		$datas = URequest::getInput ();
49
		if (sizeof ( $datas ) > 0) {
50
			$datas = current ( array_keys ( $datas ) );
51
			$datas = json_decode ( $datas, true );
52
			$attributes = $datas ["data"] ["attributes"] ?? [ ];
53
			if (isset ( $datas ["id"] )) {
54
				$key = OrmUtils::getFirstKey ( $this->model );
55
				$attributes [$key] = $datas ["id"];
56
			}
57
			return $attributes;
58
		}
59
		$this->addError ( 204, 'No content', 'The POST request has no content!' );
60
	}
61
62
	/**
63
	 *
64
	 * @route("{resource}/","methods"=>["options"])
65
	 */
66
	public function options($resource) {
1 ignored issue
show
Unused Code introduced by
The parameter $resource is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

66
	public function options(/** @scrutinizer ignore-unused */ $resource) {

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
67
	}
68
69
	/**
70
	 *
71
	 * {@inheritdoc}
72
	 * @see \Ubiquity\controllers\rest\RestBaseController::index()
73
	 * @route("links/","methods"=>["get"])
74
	 */
75
	public function index() {
76
		parent::index ();
77
	}
78
79 1
	/**
80
	 * Returns all the instances from the model $resource.
81 1
	 * Query parameters:
82 1
	 * - **included**: A string of associated members to load, comma separated (e.g. users,groups,organization...), or a boolean: true for all members, false for none (default: true).
83 1
	 * - **filter**: The filter to apply to the query (where part of an SQL query) (default: 1=1).
84
	 * - **page[number]**: The page to display (in this case, the page size is set to 1).
85
	 * - **page[size]**: The page size (count of instance per page) (default: 1).
86
	 *
87
	 * @route("{resource}/","methods"=>["get"],"priority"=>0)
88 1
	 */
89 1
	public function getAll_($resource) {
90 1
		$this->_checkResource ( $resource, function () {
91 1
			$filter = $this->getRequestParam ( 'filter', '1=1' );
92
			$pages = null;
93
			if (isset ( $_GET ['page'] )) {
94
				$pageNumber = $_GET ['page'] ['number'];
95
				$pageSize = $_GET ['page'] ['size'] ?? 1;
96
				$pages = $this->generatePagination ( $filter, $pageNumber, $pageSize );
97
			}
98
			$datas = DAO::getAll ( $this->model, $filter, $this->getIncluded ( $this->getRequestParam ( 'included', true ) ) );
99
			echo $this->_getResponseFormatter ()->get ( $datas, $pages );
100
		} );
101
	}
102
103
	/**
104
	 * Returns an instance of $resource, by primary key $id.
105
	 * Query parameters:
106 1
	 * - **included**: A string of associated members to load, comma separated (e.g. users,groups,organization...), or a boolean: true for all members, false for none (default: true).
107
	 * - **filter**: The filter to apply to the query (where part of an SQL query) (default: 1=1).
108 1
	 *
109 1
	 * @param string $resource
110 1
	 *        	The resource (model) to use
111
	 * @param string $id
112
	 *        	The primary key value(s), if the primary key is composite, use a comma to separate the values (e.g. 1,115,AB)
113
	 *
114
	 * @route("{resource}/{id}/","methods"=>["get"],"priority"=>1000)
115
	 */
116
	public function getOne_($resource, $id) {
117
		$this->_checkResource ( $resource, function () use ($id) {
118
			$this->_getOne ( $id, true, false );
119
		} );
120
	}
121
122
	/**
123
	 * Returns an associated member value(s).
124
	 * Query parameters:
125
	 * - **included**: A string of associated members to load, comma separated (e.g. users,groups,organization...), or a boolean: true for all members, false for none (default: true).
126
	 *
127
	 * @param string $resource
128
	 *        	The resource (model) to use
129
	 * @param string $id
130
	 *        	The primary key value(s), if the primary key is composite, use a comma to separate the values (e.g. 1,115,AB)
131 1
	 * @param string $member
132 1
	 *        	The member to load
133
	 *
134
	 * @route("{resource}/{id}/relationships/{member}/","methods"=>["get"],"priority"=>2000)
135
	 */
136
	public function getRelationShip_($resource, $id, $member) {
137
		$this->_checkResource ( $resource, function () use ($id, $member) {
138
			$relations = OrmUtils::getAnnotFieldsInRelations ( $this->model );
139
			if (isset ( $relations [$member] )) {
140
				$included = $this->getRequestParam ( 'included', true );
141
				switch ($relations [$member] ['type']) {
142
					case 'manyToOne' :
143
						$this->_getManyToOne ( $id, $member, $this->getIncluded ( $included ) );
144
						break;
145
					case 'oneToMany' :
146
						$this->_getOneToMany ( $id, $member, $this->getIncluded ( $included ) );
0 ignored issues
show
Bug introduced by
It seems like $this->getIncluded($included) can also be of type string[]; however, parameter $included of Ubiquity\controllers\res...roller::_getOneToMany() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

146
						$this->_getOneToMany ( $id, $member, /** @scrutinizer ignore-type */ $this->getIncluded ( $included ) );
Loading history...
147
						break;
148
					case 'manyToMany' :
149
						$this->_getManyToMany ( $id, $member, $this->getIncluded ( $included ) );
0 ignored issues
show
Bug introduced by
It seems like $this->getIncluded($included) can also be of type string[]; however, parameter $included of Ubiquity\controllers\res...oller::_getManyToMany() does only seem to accept boolean|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

149
						$this->_getManyToMany ( $id, $member, /** @scrutinizer ignore-type */ $this->getIncluded ( $included ) );
Loading history...
150
						break;
151
				}
152
			}
153
		} );
154
	}
155
156
	/**
157
	 * Inserts a new instance of $resource.
158
	 * Data attributes are send in data[attributes] request header
159
	 *
160
	 * @param string $resource
161
	 *        	The resource (model) to use
162
	 * @route("{resource}/","methods"=>["post"],"priority"=>0)
163
	 */
164
	public function add_($resource) {
165
		$this->_checkResource ( $resource, function () {
166
			parent::add ();
167
		} );
168
	}
169
170
	/**
171
	 * Updates an existing instance of $resource.
172
	 * Data attributes are send in data[attributes] request header
173
	 *
174
	 * @param string $resource
175
	 *        	The resource (model) to use
176
	 *
177
	 * @route("{resource}/","methods"=>["patch"],"priority"=>0)
178
	 */
179
	public function update_($resource) {
180
		$this->_checkResource ( $resource, function () {
181
			$pks = $this->getPrimaryKeysFromDatas ( $this->getDatas (), $this->model );
182
			if (! $this->hasErrors ()) {
183
				parent::update ( $pks );
184
			} else {
185
				echo $this->displayErrors ();
186
			}
187
		} );
188
	}
189
190
	/**
191
	 * Deletes an existing instance of $resource.
192
	 *
193
	 * @param string $resource
194
	 *        	The resource (model) to use
195
	 * @param string $ids
196
	 *        	The primary key value(s), if the primary key is composite, use a comma to separate the values (e.g. 1,115,AB)
197
	 *
198
	 * @route("{resource}/{$id}/","methods"=>["delete"],"priority"=>0)
199
	 */
200
	public function delete_($resource, ...$id) {
201
		$this->_checkResource ( $resource, function () use ($id) {
202
			$this->delete ( $id );
203
		} );
204
	}
205
206
	/**
207
	 * Returns the api version
208
	 *
209
	 * @return string
210
	 */
211
	public static function _getApiVersion() {
212
		return self::API_VERSION;
213
	}
214
}
215
216