Completed
Push — master ( d41a4c...e7d4d2 )
by Elan
22s queued 10s
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
    public function convert(array $options): array
16
    {
17
        $result = [
18
            'conditions' => [],
19
            'sort' => null,
20
            'direction' => null,
21
            'perPage' => 25,
22
        ];
23
        if (isset($options['conditions'])) {
24
            $result['conditions'] = $this->buildConditions($options['conditions']);
25
        }
26
        $result['direction'] = $this->buildDirection($options);
27
        $result['sort'] = $this->buildSort($options);
28
29
        if (isset($options['perPage'])) {
30
            $result['perPage'] = $options['perPage'];
31
        }
32
33
        return $result;
34
    }
35
36
    /**
37
     * Convert the search parameters into the matching fields.
38
     *
39
     * Keeps the schema details out of the GET parameters.
40
     * String casts are uses to prevent mongo operator injection.
41
     */
42
    private function buildConditions(array $search): array
43
    {
44 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...
45
            $search['limit'] = $search['limit_custom'];
46
        }
47
        $hasLimit = (!empty($search['limit']) && $search['limit'] != -1);
48
49
        $conditions = [];
50 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...
51
            $conditions['meta.request_date']['$gte'] = (string)$search['date_start'];
52
        }
53 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...
54
            $conditions['meta.request_date']['$lte'] = (string)$search['date_end'];
55
        }
56
        if (isset($search['simple_url'])) {
57
            $conditions['meta.simple_url'] = (string)$search['simple_url'];
58
        }
59 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...
60
            $conditions['meta.SERVER.REQUEST_TIME']['$gte'] = $this->convertDate($search['request_start']);
61
        }
62 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...
63
            $conditions['meta.SERVER.REQUEST_TIME']['$lte'] = $this->convertDate($search['request_end']);
64
        }
65
66
        if (!empty($search['remote_addr'])) {
67
            $conditions['meta.SERVER.REMOTE_ADDR'] = (string)$search['remote_addr'];
68
        }
69
        if (isset($search['cookie'])) {
70
            $conditions['meta.SERVER.HTTP_COOKIE'] = (string)$search['cookie'];
71
        }
72
73
        if ($hasLimit && $search['limit'][0] === 'P') {
74
            $date = new DateTime();
75
            try {
76
                $date->sub(new DateInterval($search['limit']));
77
                $conditions['meta.request_ts']['$gte'] = new MongoDate($date->getTimestamp());
78
            } catch (\Exception $e) {
79
                // Match a day in the future so we match nothing, as it's likely an invalid format
80
                $conditions['meta.request_ts']['$gte'] = new MongoDate(time() + 86400);
81
            }
82
        }
83
84
        if (isset($search['url'])) {
85
            // Not sure if letting people use regex here
86
            // is a good idea. Only one way to find out.
87
            $conditions['meta.url'] = [
88
                '$regex' => (string)$search['url'],
89
                '$options' => 'i',
90
            ];
91
        }
92
93
        return $conditions;
94
    }
95
96
    private function convertDate($dateString)
97
    {
98
        if (is_numeric($dateString)) {
99
            return (float) $dateString;
100
        }
101
        $date = DateTime::createFromFormat('Y-m-d H:i:s', $dateString);
102
        if (!$date) {
103
            return $date;
104
        }
105
106
        return $date->getTimestamp();
107
    }
108
109
    private function buildDirection(array $options): string
110
    {
111
        if (empty($options['direction'])) {
112
            return SearcherInterface::DEFAULT_DIRECTION;
113
        }
114
        $valid = ['desc', 'asc'];
115
        if (in_array($options['direction'], $valid, true)) {
116
            return $options['direction'];
117
        }
118
119
        return 'desc';
120
    }
121
122
    /**
123
     * Get sort options for a paginated set.
124
     *
125
     * Whitelists to valid known keys.
126
     *
127
     * @param array $options pagination options including the sort key
128
     * @return array sort field & direction
129
     */
130
    private function buildSort(array $options): array
131
    {
132
        $direction = -1;
133
        if (isset($options['direction']) && $options['direction'] === 'asc') {
134
            $direction = 1;
135
        }
136
137
        $valid = ['time', 'wt', 'mu', 'cpu'];
138
        if (
139
            empty($options['sort']) ||
140
            (isset($options['sort']) && !in_array($options['sort'], $valid))
141
        ) {
142
            return ['meta.SERVER.REQUEST_TIME' => $direction];
143
        }
144
        if ($options['sort'] === 'time') {
145
            return ['meta.SERVER.REQUEST_TIME' => $direction];
146
        } elseif ($options['sort'] === 'wt') {
147
            return ['profile.main().wt' => $direction];
148
        } elseif ($options['sort'] === 'mu') {
149
            return ['profile.main().mu' => $direction];
150
        } elseif ($options['sort'] === 'cpu') {
151
            return ['profile.main().cpu' => $direction];
152
        }
153
    }
154
}
155