1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* tubee.io |
7
|
|
|
* |
8
|
|
|
* @copyright Copryright (c) 2017-2019 gyselroth GmbH (https://gyselroth.com) |
9
|
|
|
* @license GPL-3.0 https://opensource.org/licenses/GPL-3.0 |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Tubee\Rest\Middlewares; |
13
|
|
|
|
14
|
|
|
use function MongoDB\BSON\fromJSON; |
15
|
|
|
use function MongoDB\BSON\toPHP; |
16
|
|
|
use Psr\Http\Message\ResponseInterface; |
17
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
18
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
19
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
20
|
|
|
use Tubee\Rest\Exception; |
21
|
|
|
use Zend\Diactoros\Response; |
22
|
|
|
|
23
|
|
|
class QueryDecoder implements MiddlewareInterface |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* Process a server request and return a response. |
27
|
|
|
*/ |
28
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
29
|
|
|
{ |
30
|
|
|
$query = $request->getQueryParams(); |
31
|
|
|
|
32
|
|
|
if (isset($query['offset'])) { |
33
|
|
|
$query['offset'] = (int) $query['offset']; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if (isset($query['limit'])) { |
37
|
|
|
$query['limit'] = (int) $query['limit']; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
View Code Duplication |
if (isset($query['watch']) && !empty($query['watch']) && $query['watch'] !== 'false') { |
|
|
|
|
41
|
|
|
$query['watch'] = true; |
42
|
|
|
} else { |
43
|
|
|
$query['watch'] = null; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (isset($query['query'])) { |
47
|
|
|
$query['query'] = toPHP(fromJSON($query['query']), [ |
48
|
|
|
'root' => 'array', |
49
|
|
|
'document' => 'array', |
50
|
|
|
'array' => 'array', |
51
|
|
|
]); |
52
|
|
|
} else { |
53
|
|
|
$query['query'] = []; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
View Code Duplication |
if (isset($query['stream']) && $query['stream'] !== 'false' && !empty($query['stream']) && !isset($query['limit'])) { |
|
|
|
|
57
|
|
|
$query['limit'] = null; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
if (isset($query['sort'])) { |
61
|
|
|
$query['sort'] = json_decode(htmlspecialchars_decode($query['sort']), true); |
62
|
|
|
|
63
|
|
|
if (json_last_error()) { |
64
|
|
|
throw new Exception\InvalidInput('failed to decode provided sort: '.json_last_error_msg().', sort needs to be valid json'); |
65
|
|
|
} |
66
|
|
|
} else { |
67
|
|
|
$query['sort'] = []; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$request = $request->withQueryParams($query); |
71
|
|
|
|
72
|
|
|
return $handler->handle($request); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.