ApiRoute   B
last analyzed

Complexity

Total Complexity 53

Size/Duplication

Total Lines 397
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 53
lcom 1
cbo 7
dl 0
loc 397
rs 7.4757
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 38 6
A setPresenter() 0 4 1
A getPresenter() 0 4 1
A setAction() 0 12 3
A prepareForMatch() 0 4 1
A getPlacehodlerParameters() 0 14 2
A getRequiredParams() 0 17 2
A resolveFormat() 0 18 4
A getFormatFull() 0 4 1
A setMethods() 0 14 4
A getMethods() 0 4 1
A resolveMethod() 0 14 4
D match() 0 108 14
C constructUrl() 0 46 9

How to fix   Complexity   

Complex Class

Complex classes like ApiRoute often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ApiRoute, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright   Copyright (c) 2016 ublaboo <[email protected]>
7
 * @author      Pavel Janda <[email protected]>
8
 * @package     Ublaboo
9
 */
10
11
namespace Ublaboo\ApiRouter;
12
13
use Nette;
14
use Nette\Application\IRouter;
15
use Nette\Application\Request;
16
use Nette\SmartObject;
17
use Nette\Utils\Strings;
18
19
/**
20
 * @method mixed onMatch(static, Nette\Application\Request $request)
21
 * 
22
 * @Annotation
23
 * @Target({"CLASS", "METHOD"})
24
 */
25
class ApiRoute extends ApiRouteSpec implements IRouter
26
{
27
	use SmartObject;
28
29
	/**
30
	 * @var callable[]
31
	 */
32
	public $onMatch;
33
34
	/**
35
	 * @var string|null
36
	 */
37
	private $presenter;
38
39
	/**
40
	 * @var array
41
	 */
42
	private $actions = [
43
		'POST' => false,
44
		'GET' => false,
45
		'PUT' => false,
46
		'DELETE' => false,
47
		'OPTIONS' => false,
48
		'PATCH' => false,
49
	];
50
51
	/**
52
	 * @var array
53
	 */
54
	private $default_actions = [
55
		'POST' => 'create',
56
		'GET' => 'read',
57
		'PUT' => 'update',
58
		'DELETE' => 'delete',
59
		'OPTIONS' => 'options',
60
		'PATCH' => 'patch',
61
	];
62
63
	/**
64
	 * @var array
65
	 */
66
	private $formats = [
67
		'json' => 'application/json',
68
		'xml' => 'application/xml',
69
	];
70
71
	/**
72
	 * @var array
73
	 */
74
	private $placeholder_order = [];
75
76
77
	public function __construct($path, string $presenter = null, array $data = [])
78
	{
79
		/**
80
		 * Interface for setting route via annotation or directly
81
		 */
82
		if (!is_array($path)) {
83
			$data['value'] = $path;
84
			$data['presenter'] = $presenter;
85
86
			if (empty($data['methods'])) {
87
				$this->actions = $this->default_actions;
88
			} else {
89
				foreach ($data['methods'] as $method => $action) {
90
					if (is_string($method)) {
91
						$this->setAction($action, $method);
92
					} else {
93
						$m = $action;
94
95
						if (isset($this->default_actions[$m])) {
96
							$this->setAction($this->default_actions[$m], $m);
97
						}
98
					}
99
				}
100
101
				unset($data['methods']);
102
			}
103
		} else {
104
			$data = $path;
105
		}
106
107
		/**
108
		 * Set Path
109
		 */
110
		$this->setPath($data['value']);
111
		unset($data['value']);
112
113
		parent::__construct($data);
114
	}
115
116
117
	public function setPresenter(?string $presenter): void
118
	{
119
		$this->presenter = $presenter;
120
	}
121
122
123
	public function getPresenter(): ?string
124
	{
125
		return $this->presenter;
126
	}
127
128
129
	public function setAction(string $action, string $method = null): void
130
	{
131
		if ($method === null) {
132
			$method = array_search($action, $this->default_actions, true);
133
		}
134
135
		if (!isset($this->default_actions[$method])) {
136
			return;
137
		}
138
139
		$this->actions[$method] = $action;
140
	}
141
142
143
	private function prepareForMatch(string $string): string
144
	{
145
		return sprintf('/%s/', str_replace('/', '\/', $string));
146
	}
147
148
149
	/**
150
	 * Get all parameters from url mask
151
	 */
152
	public function getPlacehodlerParameters(): array
153
	{
154
		if (!empty($this->placeholder_order)) {
155
			return array_filter($this->placeholder_order);
156
		}
157
158
		$return = [];
159
160
		preg_replace_callback('/<(\w+)>/', function ($item) use (&$return) {
161
			$return[] = end($item);
162
		}, $this->path);
163
164
		return $return;
165
	}
166
167
168
	/**
169
	 * Get required parameters from url mask
170
	 */
171
	public function getRequiredParams(): array
172
	{
173
		$regex = '/\[[^\[]+?\]/';
174
		$path = $this->getPath();
175
176
		while (preg_match($regex, $path)) {
177
			$path = preg_replace($regex, '', $path);
178
		}
179
180
		$required = [];
181
182
		preg_replace_callback('/<(\w+)>/', function ($item) use (&$required) {
183
			$required[] = end($item);
184
		}, $path);
185
186
		return $required;
187
	}
188
189
190
	public function resolveFormat(Nette\Http\IRequest $httpRequest): void
191
	{
192
		if ($this->getFormat()) {
193
			return;
194
		}
195
196
		$header = $httpRequest->getHeader('Accept');
197
198
		foreach ($this->formats as $format => $format_full) {
199
			$format_full = Strings::replace($format_full, '/\//', '\/');
200
201
			if (Strings::match($header, "/{$format_full}/")) {
202
				$this->setFormat($format);
203
			}
204
		}
205
206
		$this->setFormat('json');
207
	}
208
209
210
	public function getFormatFull(): string
211
	{
212
		return $this->formats[$this->getFormat()];
213
	}
214
215
216
	public function setMethods(array $methods)
217
	{
218
		foreach ($methods as $method => $action) {
219
			if (is_string($method)) {
220
				$this->setAction($action, $method);
221
			} else {
222
				$m = $action;
223
224
				if (isset($this->default_actions[$m])) {
225
					$this->setAction($this->default_actions[$m], $m);
226
				}
227
			}
228
		}
229
	}
230
231
232
	public function getMethods(): array
233
	{
234
		return array_keys(array_filter($this->actions));
235
	}
236
237
238
	public function resolveMethod(Nette\Http\IRequest $request): string
239
	{
240
		if (!empty($request->getHeader('X-HTTP-Method-Override'))) {
241
			return Strings::upper($request->getHeader('X-HTTP-Method-Override'));
242
		}
243
244
		if ($method = Strings::upper($request->getQuery('__apiRouteMethod'))) {
245
			if (isset($this->actions[$method])) {
246
				return $method;
247
			}
248
		}
249
250
		return Strings::upper($request->getMethod());
251
	}
252
253
254
	/********************************************************************************
255
	 *                              Interface IRouter                               *
256
	 ********************************************************************************/
257
258
259
	/**
260
	 * Maps HTTP request to a Request object.
261
	 */
262
	public function match(Nette\Http\IRequest $httpRequest): ?Request
263
	{
264
		/**
265
		 * ApiRoute can be easily disabled
266
		 */
267
		if ($this->disable) {
268
			return null;
269
		}
270
271
		$url = $httpRequest->getUrl();
272
273
		$path = $url->getPath();
274
275
		/**
276
		 * Build path mask
277
		 */
278
		$order = &$this->placeholder_order;
279
		$parameters = $this->parameters;
280
281
		$mask = preg_replace_callback('/(<(\w+)>)|\[|\]/', function ($item) use (&$order, $parameters) {
282
			if ($item[0] == '[' || $item[0] == ']') {
283
				if ($item[0] == '[') {
284
					$order[] = null;
285
				}
286
287
				return $item[0];
288
			}
289
290
			[, , $placeholder] = $item;
0 ignored issues
show
Bug introduced by
The variable $placeholder does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
291
292
			$parameter = $parameters[$placeholder] ?? [];
293
294
			$regex = $parameter['requirement'] ?? '\w+';
295
			$has_default = array_key_exists('default', $parameter);
296
			$regex = preg_replace('~\(~', '(?:', $regex);
297
298
			if ($has_default) {
299
				$order[] = $placeholder;
300
301
				return sprintf('(%s)?', $regex);
302
			}
303
304
			$order[] = $placeholder;
305
306
			return sprintf('(%s)', $regex);
307
		}, $this->path);
308
309
		$mask = '^' . str_replace(['[', ']'], ['(', ')?'], $mask) . '$';
310
311
		/**
312
		 * Prepare paths for regex match (escape slashes)
313
		 */
314
		if (!preg_match_all($this->prepareForMatch($mask), $path, $matches)) {
315
			return null;
316
		}
317
318
		/**
319
		 * Did some action to the request method exists?
320
		 */
321
		$this->resolveFormat($httpRequest);
322
		$method = $this->resolveMethod($httpRequest);
323
		$action = $this->actions[$method];
324
325
		if (!$action) {
326
			return null;
327
		}
328
329
		/**
330
		 * Basic params
331
		 */
332
		$params = $httpRequest->getQuery();
333
		$params['action'] = $action;
334
		$required_params = $this->getRequiredParams();
335
336
		/**
337
		 * Route mask parameters
338
		 */
339
		array_shift($matches);
340
341
		foreach ($this->placeholder_order as $key => $name) {
342
			if ($name !== null&& isset($matches[$key])) {
343
				$params[$name] = reset($matches[$key]) ?: null;
344
345
				/**
346
				 * Required parameters
347
				 */
348
				if (empty($params[$name]) && in_array($name, $required_params, true)) {
349
					return null;
350
				}
351
			}
352
		}
353
354
		$request = new Request(
355
			$this->presenter,
356
			$method,
357
			$params,
358
			$httpRequest->getPost(),
359
			$httpRequest->getFiles(),
360
			[Request::SECURED => $httpRequest->isSecured()]
361
		);
362
363
		/**
364
		 * Trigger event - route matches
365
		 */
366
		$this->onMatch($this, $request);
367
368
		return $request;
369
	}
370
371
372
	/**
373
	 * Constructs absolute URL from Request object.
374
	 */
375
	public function constructUrl(Request $request, Nette\Http\Url $url): ?string
376
	{
377
		if ($this->presenter != $request->getPresenterName()) {
378
			return null;
379
		}
380
381
		$base_url = $url->getBaseUrl();
382
383
		$action = $request->getParameter('action');
384
		$parameters = $request->getParameters();
385
		unset($parameters['action']);
386
		$path = ltrim($this->getPath(), '/');
387
388
		if (array_search($action, $this->actions, true) === false) {
389
			return null;
390
		}
391
392
		foreach ($parameters as $name => $value) {
393
			if (strpos($path, "<{$name}>") !== false && $value !== null) {
394
				$path = str_replace("<{$name}>", $value, $path);
395
396
				unset($parameters[$name]);
397
			}
398
		}
399
400
		$path = preg_replace_callback('/\[.+?\]/', function ($item) {
401
			if (strpos(end($item), '<')) {
402
				return '';
403
			}
404
405
			return end($item);
406
		}, $path);
407
408
		/**
409
		 * There are still some required parameters in url mask
410
		 */
411
		if (preg_match('/<\w+>/', $path)) {
412
			return null;
413
		}
414
415
		$path = str_replace(['[', ']'], '', $path);
416
417
		$query = http_build_query($parameters);
418
419
		return $base_url . $path . ($query ? '?' . $query : '');
420
	}
421
}
422