Completed
Pull Request — master (#368)
by Elan
01:33
created

Mapper::buildSort()   B

Complexity

Conditions 10
Paths 12

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 7.6666
c 0
b 0
f 0
cc 10
nc 12
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace XHGui\Db;
4
5
use DateInterval;
6
use DateTime;
7
use MongoDate;
8
use XHGui\Searcher\SearcherInterface;
9
10
class Mapper
11
{
12
    /**
13
     * Convert request data keys into mongo values.
14
     *
15
     * @param array $options
16
     * @return array
17
     */
18
    public function convert(array $options): array
19
    {
20
        $result = [
21
            'conditions' => [],
22
            'sort' => null,
23
            'direction' => null,
24
            'perPage' => 25,
25
        ];
26
        if (isset($options['conditions'])) {
27
            $result['conditions'] = $this->buildConditions($options['conditions']);
28
        }
29
        $result['direction'] = $this->buildDirection($options);
30
        $result['sort'] = $this->buildSort($options);
31
32
        if (isset($options['perPage'])) {
33
            $result['perPage'] = $options['perPage'];
34
        }
35
36
        return $result;
37
    }
38
39
    /**
40
     * Convert the search parameters into the matching fields.
41
     *
42
     * Keeps the schema details out of the GET parameters.
43
     * String casts are uses to prevent mongo operator injection.
44
     *
45
     * @param array $search
46
     * @return array
47
     */
48
    private function buildConditions(array $search): array
49
    {
50 View Code Duplication
        if (!empty($search['limit_custom']) && $search['limit_custom'][0] === 'P') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
51
            $search['limit'] = $search['limit_custom'];
52
        }
53
        $hasLimit = (!empty($search['limit']) && $search['limit'] != -1);
54
55
        $conditions = [];
56 View Code Duplication
        if (!empty($search['date_start']) && !$hasLimit) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
57
            $conditions['meta.request_date']['$gte'] = (string)$search['date_start'];
58
        }
59 View Code Duplication
        if (!empty($search['date_end']) && !$hasLimit) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
60
            $conditions['meta.request_date']['$lte'] = (string)$search['date_end'];
61
        }
62
        if (isset($search['simple_url'])) {
63
            $conditions['meta.simple_url'] = (string)$search['simple_url'];
64
        }
65 View Code Duplication
        if (!empty($search['request_start'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
66
            $conditions['meta.SERVER.REQUEST_TIME']['$gte'] = $this->convertDate($search['request_start']);
67
        }
68 View Code Duplication
        if (!empty($search['request_end'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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.

Loading history...
69
            $conditions['meta.SERVER.REQUEST_TIME']['$lte'] = $this->convertDate($search['request_end']);
70
        }
71
72
        if (!empty($search['remote_addr'])) {
73
            $conditions['meta.SERVER.REMOTE_ADDR'] = (string)$search['remote_addr'];
74
        }
75
        if (isset($search['cookie'])) {
76
            $conditions['meta.SERVER.HTTP_COOKIE'] = (string)$search['cookie'];
77
        }
78
79
        if ($hasLimit && $search['limit'][0] === 'P') {
80
            $date = new DateTime();
81
            try {
82
                $date->sub(new DateInterval($search['limit']));
83
                $conditions['meta.request_ts']['$gte'] = new MongoDate($date->getTimestamp());
84
            } catch (\Exception $e) {
85
                // Match a day in the future so we match nothing, as it's likely an invalid format
86
                $conditions['meta.request_ts']['$gte'] = new MongoDate(time() + 86400);
87
            }
88
        }
89
90
        if (isset($search['url'])) {
91
            // Not sure if letting people use regex here
92
            // is a good idea. Only one way to find out.
93
            $conditions['meta.url'] = [
94
                '$regex' => (string)$search['url'],
95
                '$options' => 'i',
96
            ];
97
        }
98
99
        return $conditions;
100
    }
101
102
    private function convertDate($dateString)
103
    {
104
        if (is_numeric($dateString)) {
105
            return (float) $dateString;
106
        }
107
        $date = DateTime::createFromFormat('Y-m-d H:i:s', $dateString);
108
        if (!$date) {
109
            return $date;
110
        }
111
112
        return $date->getTimestamp();
113
    }
114
115
    private function buildDirection(array $options): string
116
    {
117
        if (empty($options['direction'])) {
118
            return SearcherInterface::DEFAULT_DIRECTION;
119
        }
120
        $valid = ['desc', 'asc'];
121
        if (in_array($options['direction'], $valid, true)) {
122
            return $options['direction'];
123
        }
124
125
        return 'desc';
126
    }
127
128
    /**
129
     * Get sort options for a paginated set.
130
     *
131
     * Whitelists to valid known keys.
132
     *
133
     * @param array $options pagination options including the sort key
134
     * @return array sort field & direction
135
     */
136
    protected function buildSort(array $options): array
137
    {
138
        $direction = -1;
139
        if (isset($options['direction']) && $options['direction'] === 'asc') {
140
            $direction = 1;
141
        }
142
143
        $valid = ['time', 'wt', 'mu', 'cpu'];
144
        if (
145
            empty($options['sort']) ||
146
            (isset($options['sort']) && !in_array($options['sort'], $valid))
147
        ) {
148
            return ['meta.SERVER.REQUEST_TIME' => $direction];
149
        }
150
        if ($options['sort'] === 'time') {
151
            return ['meta.SERVER.REQUEST_TIME' => $direction];
152
        } elseif ($options['sort'] === 'wt') {
153
            return ['profile.main().wt' => $direction];
154
        } elseif ($options['sort'] === 'mu') {
155
            return ['profile.main().mu' => $direction];
156
        } elseif ($options['sort'] === 'cpu') {
157
            return ['profile.main().cpu' => $direction];
158
        }
159
    }
160
}
161