Completed
Push — master ( 743575...aa2450 )
by Stefano
20s queued 11s
created

QueryComponent::index()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 14
rs 10
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2021 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace App\Controller\Component;
14
15
use Cake\Controller\Component;
16
use Cake\Utility\Hash;
17
18
/**
19
 * Handles query strings.
20
 */
21
class QueryComponent extends Component
22
{
23
    /**
24
     * Retrieve `index` module query string array
25
     *
26
     * @return array
27
     */
28
    public function index(): array
29
    {
30
        $query = (array)$this->getController()->getRequest()->getQueryParams();
31
32
        // return URL query string if `filter`, `sort`, or `q` are set
33
        $subQuery = array_intersect_key($query, array_flip(['filter', 'sort', 'q']));
34
        if (!empty($subQuery)) {
35
            return $query;
36
        }
37
38
        // set sort order: use `currentModule.sort` or default '-id'
39
        $query['sort'] = (string)Hash::get($this->getController()->viewVars, 'currentModule.sort', '-id');
40
41
        return $query;
42
    }
43
44
    /**
45
     * Prepare query string to make BE4 API call
46
     *
47
     * @param array $query Input query string
48
     * @return array
49
     */
50
    public function prepare(array $query): array
51
    {
52
        // cleanup `filter`, remove empty keys
53
        $filter = array_filter((array)Hash::get($query, 'filter'));
54
        $remove = array_flip(['count', 'page_items', 'page_count', 'filter']);
55
        $query = array_diff_key($query, $remove);
56
        if (!empty($filter)) {
57
            $query += compact('filter');
58
        }
59
60
        return $query;
61
    }
62
}
63