Completed
Push — master ( 04aca3...4b3d1a )
by
unknown
03:17
created

TransformSortingParametersListener   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 31
rs 10
c 0
b 0
f 0
lcom 0
cbo 3

1 Method

Rating   Name   Duplication   Size   Complexity  
B onKernelRequest() 0 28 6
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\JsonApi\EventListener;
15
16
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
17
18
/**
19
 * @see http://jsonapi.org/format/#fetching-sorting
20
 * @see https://api-platform.com/docs/core/filters#order-filter
21
 *
22
 * @author Héctor Hurtarte <[email protected]>
23
 * @author Baptiste Meyer <[email protected]>
24
 */
25
final class TransformSortingParametersListener
26
{
27
    public function onKernelRequest(GetResponseEvent $event)
28
    {
29
        $request = $event->getRequest();
30
31
        if (
32
            'jsonapi' !== $request->getRequestFormat() ||
33
            null === ($orderParameter = $request->query->get('sort')) ||
34
            is_array($orderParameter)
35
        ) {
36
            return;
37
        }
38
39
        $orderParametersArray = explode(',', $orderParameter);
40
        $transformedOrderParametersArray = [];
41
42
        foreach ($orderParametersArray as $orderParameter) {
43
            $sorting = 'asc';
44
45
            if ('-' === substr($orderParameter, 0, 1)) {
46
                $sorting = 'desc';
47
                $orderParameter = substr($orderParameter, 1);
48
            }
49
50
            $transformedOrderParametersArray[$orderParameter] = $sorting;
51
        }
52
53
        $request->attributes->set('_api_filter_order', $transformedOrderParametersArray);
54
    }
55
}
56