Completed
Push — master ( d41a4c...e7d4d2 )
by Elan
22s queued 10s
created

Mapper   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 145
Duplicated Lines 10.34 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 0
dl 15
loc 145
rs 9.52
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A convert() 0 20 3
F buildConditions() 15 53 17
A convertDate() 0 12 3
A buildDirection() 0 12 3
B buildSort() 0 24 10

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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