Completed
Pull Request — master (#331)
by Elan
02:10 queued 57s
created

Xhgui_Db_Mapper::_conditions()   F

Complexity

Conditions 17
Paths 4096

Size

Total Lines 53

Duplication

Lines 15
Ratio 28.3 %

Importance

Changes 0
Metric Value
dl 15
loc 53
rs 1.0499
c 0
b 0
f 0
cc 17
nc 4096
nop 1

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