Completed
Push — master ( ec18ae...5b38d7 )
by Felix
10:07
created

StatKeywords   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 199
Duplicated Lines 13.57 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 7
dl 27
loc 199
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B list() 0 33 5
C create() 2 34 7
A delete() 0 20 3
A transformCreatedKeyword() 0 11 1
B transformListedKeyword() 25 63 5

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 SchulzeFelix\Stat\Api;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Collection;
7
use SchulzeFelix\Stat\Objects\StatKeyword;
8
use SchulzeFelix\Stat\Objects\StatKeywordEngineRanking;
9
use SchulzeFelix\Stat\Objects\StatKeywordRanking;
10
use SchulzeFelix\Stat\Objects\StatKeywordStats;
11
use SchulzeFelix\Stat\Objects\StatLocalSearchTrend;
12
13
class StatKeywords extends BaseStat
14
{
15
    /**
16
     * @param $siteID
17
     * @return Collection
18
     */
19
    public function list($siteID) : Collection
20
    {
21
        $start = 0;
22
        $keywords = collect();
23
24
        do {
25
            $response = $this->performQuery('keywords/list', ['site_id' => $siteID, 'start' => $start, 'results' => 5000 ]);
26
            $start += 5000;
27
28
            if($response['totalresults'] == 0) {
29
                break;
30
            }
31
32
            if(isset($response['Result']['Id'])) {
33
                $keywords->push($response['Result']);
34
            }
35
36
            $keywords = $keywords->merge($response['Result']);
37
38
            if (!isset($response['nextpage'])) {
39
                break;
40
            }
41
42
        } while ($response['resultsreturned'] < $response['totalresults']);
43
44
45
        $keywords = $keywords->transform(function ($keyword, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
46
                return $this->transformListedKeyword($keyword);
47
        });
48
49
        return $keywords;
50
51
    }
52
53
    /**
54
     * @param $siteID
55
     * @param $market
56
     * @param array $keywords
57
     * @param array|null $tags
58
     * @param null $location
59
     * @param string $device
60
     * @return Collection
61
     */
62
    public function create($siteID, $market, array $keywords, array $tags = null, $location = null, $device = 'Desktop') : Collection
63
    {
64
        $arguments['site_id'] = $siteID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$arguments was never initialized. Although not strictly required by PHP, it is generally a good practice to add $arguments = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
65
        $arguments['market'] = $market;
66
        $arguments['device'] = $device;
67
        $arguments['type'] = 'regular';
68
        $arguments['keyword'] = implode(',', array_map(function ($el) {
69
                                    return str_replace(',', '\,', $el);
70
                                }, $keywords));
71
72 View Code Duplication
        if( ! is_null($tags) && count($tags) > 0)
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...
73
            $arguments['tag'] = implode(',', $tags);
74
75
        if( ! is_null($location) && $location != '')
76
            $arguments['location'] = $location;
77
78
        $response = $this->performQuery('keywords/create', $arguments);
79
80
        $keywords = collect();
81
82
        if($response['resultsreturned'] == 0) {
83
            return $keywords;
84
        }
85
        if($response['resultsreturned'] == 1) {
86
            $keywords->push($response['Result']);
87
        } else {
88
            $keywords = collect($response['Result']);
89
        }
90
91
        return $keywords->transform(function ($keyword, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
92
            return $this->transformCreatedKeyword($keyword);
93
        });
94
95
    }
96
97
    /**
98
     * @param int|array $id
99
     * @return Collection
100
     */
101
    public function delete($id)
102
    {
103
        if(!is_array($id)) {
104
            $id = [$id];
105
        }
106
107
        $ids = implode(',', $id);
108
109
        $response = $this->performQuery('keywords/delete', ['id' => $ids]);
110
111
        if(isset($response['Result']['Id'])){
112
            return collect($response['Result']['Id']);
113
        }
114
115
116
        return collect($response['Result'])->transform(function ($keywordID, $key) {
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
117
            return $keywordID['Id'];
118
        });
119
120
    }
121
122
123
    /**
124
     * @param $keyword
125
     * @return mixed
126
     */
127
    protected function transformCreatedKeyword($keyword) {
128
129
        return new StatKeyword([
130
            'id' => $keyword['Id'],
131
            'keyword' => $keyword['Keyword'],
132
            'keyword_market' => $keyword['KeywordMarket'],
133
            'keyword_location' => $keyword['KeywordLocation'],
134
            'keyword_device' => $keyword['KeywordDevice'],
135
            'created_at' => $keyword['CreatedAt'],
136
        ]);
137
    }
138
139
140
    /**
141
     * @param $keyword
142
     * @return mixed
143
     */
144
    protected function transformListedKeyword($keyword) {
145
        $modifiedKeyword = new StatKeyword();
146
        $modifiedKeyword->id = $keyword['Id'];
147
        $modifiedKeyword->keyword = $keyword['Keyword'];
148
        $modifiedKeyword->keyword_market = $keyword['KeywordMarket'];
149
        $modifiedKeyword->keyword_location = $keyword['KeywordLocation'];
150
        $modifiedKeyword->keyword_device = $keyword['KeywordDevice'];
151
152
153 View Code Duplication
        if($keyword['KeywordTags'] == 'none') {
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...
154
            $modifiedKeyword->keyword_tags = collect();
155
        } else {
156
            $modifiedKeyword->keyword_tags = collect(explode(',', $keyword['KeywordTags']));
157
        }
158
159 View Code Duplication
        if( is_null($keyword['KeywordStats']) ) {
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...
160
            $modifiedKeyword->keyword_stats = null;
161
        } else {
162
163
            $localTrends = collect($keyword['KeywordStats']['LocalSearchTrendsByMonth'])->map(function ($searchVolume, $month){
164
                return new StatLocalSearchTrend([
165
                    'month' => strtolower($month),
166
                    'search_volume' => ($searchVolume == '-') ? null : $searchVolume,
167
                ]);
168
            });
169
170
            $modifiedKeyword->keyword_stats = new StatKeywordStats([
171
                'advertiser_competition' => $keyword['KeywordStats']['AdvertiserCompetition'],
172
                'global_search_volume' => $keyword['KeywordStats']['GlobalSearchVolume'],
173
                'regional_search_volume' => $keyword['KeywordStats']['RegionalSearchVolume'],
174
                'cpc' => $keyword['KeywordStats']['CPC'],
175
                'local_search_trends_by_month' => $localTrends->values(),
176
            ]);
177
178
        }
179
180
        if( is_null($keyword['KeywordRanking']) ) {
181
            $modifiedKeyword->keyword_ranking = null;
182
        } else {
183
184
            $modifiedKeyword->keyword_ranking = new StatKeywordRanking([
185
                'date' => $keyword['KeywordRanking']['date'],
186
                'google' => new StatKeywordEngineRanking([
187
                    'rank' => $keyword['KeywordRanking']['Google']['Rank'],
188
                    'base_rank' => $keyword['KeywordRanking']['Google']['BaseRank'],
189
                    'url' => $keyword['KeywordRanking']['Google']['Url'],
190
                ]),
191
                'yahoo' => new StatKeywordEngineRanking([
192
                    'rank' => $keyword['KeywordRanking']['Yahoo']['Rank'],
193
                    'url' => $keyword['KeywordRanking']['Yahoo']['Url'],
194
                ]),
195
                'bing' => new StatKeywordEngineRanking([
196
                    'rank' => $keyword['KeywordRanking']['Bing']['Rank'],
197
                    'url' => $keyword['KeywordRanking']['Bing']['Url'],
198
                ]),
199
            ]);
200
201
        }
202
203
        $modifiedKeyword->created_at = $keyword['CreatedAt'];
204
205
        return $modifiedKeyword;
206
    }
207
208
209
210
211
}
212