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

StatBulk::status()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.8571
c 0
b 0
f 0
cc 2
eloc 17
nc 2
nop 1
1
<?php
2
3
namespace SchulzeFelix\Stat\Api;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Collection;
7
use Illuminate\Support\Facades\Cache;
8
use SchulzeFelix\Stat\Exceptions\ApiException;
9
use SchulzeFelix\Stat\Objects\StatBulkJob;
10
use SchulzeFelix\Stat\Objects\StatKeyword;
11
use SchulzeFelix\Stat\Objects\StatKeywordEngineRanking;
12
use SchulzeFelix\Stat\Objects\StatKeywordRanking;
13
use SchulzeFelix\Stat\Objects\StatKeywordStats;
14
use SchulzeFelix\Stat\Objects\StatLocalSearchTrend;
15
use SchulzeFelix\Stat\Objects\StatProject;
16
use SchulzeFelix\Stat\Objects\StatSite;
17
use SchulzeFelix\Stat\Objects\StatTag;
18
19
class StatBulk extends BaseStat
20
{
21
22
    public function list()
23
    {
24
        $response = $this->performQuery('bulk/list');
25
26
        $bulkJobs = collect();
27
28
        if($response['resultsreturned'] == 0) {
29
            return $bulkJobs;
30
        }
31
32
        if($response['resultsreturned'] == 1) {
33
            $bulkJobs->push($response['Result']);
34
        }
35
36
        if($response['resultsreturned'] > 1) {
37
            $bulkJobs = collect($response['Result']);
38
        }
39
40
        return $bulkJobs->transform(function ($job, $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...
41
42
            return new StatBulkJob([
43
                'id' => $job['Id'],
44
                'job_type' => $job['JobType'],
45
                'format' => $job['Format'],
46
                'date' => $job['Date'],
47
                'status' => $job['Status'],
48
                'url' => $job['Url'],
49
                'stream_url' => $job['StreamUrl'],
50
                'created_at' => $job['CreatedAt'],
51
            ]);
52
53
        });
54
    }
55
56
    /**
57
     * Schedule the creation of a new bulk export job for ranks.
58
     *
59
     * @param Carbon $date Note that you cannot create bulk jobs for the current date or dates in the future.
60
     * @param array|null $sites If no site IDs are passed in, ranks are reported for all sites in the system on the given date.
61
     * @param string $rankType This parameter changes the call between getting the highest ranks for the keywords for the date with the value 'highest', or getting all the ranks for each engine for a keyword for a date with the value 'all'.
62
     * @param array|null $engines This parameter lets you choose which search engines to include in the export, defaulting to Google, Yahoo, and Bing. Engines can be passed in a array to get multiple. ['google', 'yahoo', 'bing']
63
     * @param bool $currentlyTrackedOnly This parameter will cause the API to output only keywords which currently have tracking on at the time the API request is generated.
64
     * @param bool $crawledKeywordsOnly This parameter causes the API to only include output for keywords that were crawled on the date parameter provided.
65
     * @return int
66
     */
67
    public function ranks(Carbon $date, array $sites = null, $rankType = 'highest', $engines = null, bool $currentlyTrackedOnly = false , bool $crawledKeywordsOnly = false)
68
    {
69
        $this->validateBulkDate($date);
70
71
        $arguments['date'] = $date->toDateString();
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...
72
        $arguments['rank_type'] = $rankType;
73
        $arguments['currently_tracked_only'] = $currentlyTrackedOnly;
74
        $arguments['crawled_keywords_only'] = $crawledKeywordsOnly;
75
76
        if( ! is_null($sites) && count($sites) > 0){
77
            $arguments['site_id'] = implode(',', $sites);;
78
        }
79 View Code Duplication
        if( ! is_null($engines) && count($engines) > 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...
80
            $arguments['engines'] = implode(',', $engines);
81
        }
82
        $response = $this->performQuery('bulk/ranks', $arguments);
83
84
        return (int) $response['Result']['Id'];
85
    }
86
87
    public function status($bulkJobID)
88
    {
89
        $response = $this->performQuery('bulk/status', ['id' => $bulkJobID]);
90
91
        $jobStatus = new StatBulkJob();
92
        $jobStatus->id = $response['Result']['Id'];
93
        $jobStatus->job_type = $response['Result']['JobType'];
94
        $jobStatus->format = $response['Result']['Format'];
95
        $jobStatus->date = $response['Result']['Date'];
96
97
        $jobStatus->sites = collect();
98
        if(isset($response['Result']['SiteId'])){
99
            $jobStatus->sites = collect( explode(',', $response['Result']['SiteId']))
100
                                ->transform(function ($site, $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...
101
                                    return (int)$site;
102
                                });
103
        }
104
105
        //Current Job Status (NotStarted,InProgress,Completed,Deleted,Failed)
0 ignored issues
show
Unused Code Comprehensibility introduced by
36% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
106
        $jobStatus->status = $response['Result']['Status'];
107
        $jobStatus->url = $response['Result']['Url'] ?? null;
108
        $jobStatus->stream_url = $response['Result']['StreamUrl'] ?? null;
109
        $jobStatus->created_at = $response['Result']['CreatedAt'];
110
111
        return $jobStatus;
112
113
    }
114
115
    public function delete($bulkJobID)
116
    {
117
        $response = $this->performQuery('bulk/delete', ['id' => $bulkJobID]);
118
119
        return (int) $response['Result']['Id'];
120
    }
121
122 View Code Duplication
    public function siteRankingDistributions($date)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
123
    {
124
        $this->validateBulkDate($date);
125
126
        $response = $this->performQuery('bulk/site_ranking_distributions', ['date' => $date->toDateString()]);
127
        return (int) $response['Result']['Id'];
128
    }
129
130 View Code Duplication
    public function tagRankingDistributions($date)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
131
    {
132
        $this->validateBulkDate($date);
133
134
        $response = $this->performQuery('bulk/tag_ranking_distributions', ['date' => $date->toDateString()]);
135
        return (int) $response['Result']['Id'];
136
    }
137
138
    public function get($bulkJobID)
139
    {
140
        $bulkStatus = $this->status($bulkJobID);
141
142
        if($bulkStatus['status'] != 'Completed') {
143
            throw ApiException::resultError('Bulk Job is not completed. Current status: ' . $bulkJobID['status'] . '.');
144
        }
145
146
        $bulkStream = $this->statClient->downloadBulkJobStream($bulkStatus['stream_url']);
147
148
        return $this->parseBulkJob($bulkStream['Response']);
149
    }
150
151
    /**
152
     * @param Carbon $date
153
     * @throws ApiException
154
     */
155
    private function validateBulkDate(Carbon $date)
156
    {
157
        if ($date->isSameDay(Carbon::now()) or $date->isFuture()) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
158
            throw ApiException::resultError('You cannot create bulk jobs for the current date or dates in the future.');
159
        }
160
    }
161
162
163
    private function parseBulkJob($bulkStream)
164
    {
165
        $projects = $this->getCollection($bulkStream['Project']);
166
167
        $projects->transform(function ($project, $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...
168
            return $this->transformProject($project);
169
        });
170
171
        return $projects;
172
    }
173
174
    private function transformProject($project)
175
    {
176
        $transformedProject = new StatProject();
177
        $transformedProject->id = $project['Id'];
178
        $transformedProject->name = $project['Name'];
179
        $transformedProject->total_sites = $project['TotalSites'];
180
        $transformedProject->created_at = $project['CreatedAt'];
181
182
        if( $project['TotalSites'] == 0) {
183
            $transformedProject->sites = collect();
184
        }
185
        if( $project['TotalSites'] == 1) {
186
            $transformedProject->sites = collect([$project['Site']]);
187
        }
188
        if( $project['TotalSites'] > 1) {
189
            $transformedProject->sites = collect($project['Site']);
190
        }
191
        $transformedProject->sites->transform(function ($site, $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...
192
            return $this->transformSite($site);
193
        });
194
195
        return $transformedProject;
196
    }
197
198
199
    private function transformSite($site)
200
    {
201
        $transformedSite = new StatSite();
202
        $transformedSite->id = $site['Id'];
203
        $transformedSite->url = $site['Url'];
204
        $transformedSite->total_keywords = $site['TotalKeywords'];
205
        $transformedSite->created_at = $site['CreatedAt'];
206
207
        if(array_key_exists('Keyword', $site)){
208
209
            $transformedSite->keywords = collect($site['Keyword'])->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...
210
                return $this->transformKeyword($keyword);
211
            });
212
        }
213
214
        if(array_key_exists('RankDistribution', $site)){
215
            $transformedSite->rank_distribution = $this->transformRankDistribution($site['RankDistribution']);
216
        }
217
218
        if(array_key_exists('Tag', $site)){
219
            $transformedSite->tags = $this->getCollection($site['Tag'])->transform(function ($tag, $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...
220
                return $this->transformTag($tag);
221
            });
222
        }
223
224
225
        return $transformedSite;
226
    }
227
228
    private function transformKeyword($keyword)
229
    {
230
        $modifiedKeyword = new StatKeyword();
231
        $modifiedKeyword->id = $keyword['Id'];
232
        $modifiedKeyword->keyword = $keyword['Keyword'];
233
        $modifiedKeyword->keyword_market = $keyword['KeywordMarket'];
234
        $modifiedKeyword->keyword_location = $keyword['KeywordLocation'];
235
        $modifiedKeyword->keyword_device = $keyword['KeywordDevice'];
236
        $modifiedKeyword->keyword_categories = $keyword['KeywordCategories'];
237
238 View Code Duplication
        if(is_null($keyword['KeywordTags'])) {
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...
239
            $modifiedKeyword->keyword_tags = collect();
240
        } else {
241
            $modifiedKeyword->keyword_tags = collect(explode(',', $keyword['KeywordTags']));
242
        }
243
244 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...
245
            $modifiedKeyword->keyword_stats = null;
246
        } else {
247
            $localTrends = collect($keyword['KeywordStats']['LocalSearchTrendsByMonth'])->map(function ($searchVolume, $month){
248
                return new StatLocalSearchTrend([
249
                    'month' => strtolower($month),
250
                    'search_volume' => ($searchVolume == '-') ? null : $searchVolume,
251
                ]);
252
            });
253
254
            $modifiedKeyword->keyword_stats = new StatKeywordStats([
255
                'advertiser_competition' => $keyword['KeywordStats']['AdvertiserCompetition'],
256
                'global_search_volume' => $keyword['KeywordStats']['GlobalSearchVolume'],
257
                'targeted_search_volume' => $keyword['KeywordStats']['TargetedSearchVolume'],
258
                'cpc' => $keyword['KeywordStats']['CPC'],
259
                'local_search_trends_by_month' => $localTrends->values(),
260
            ]);
261
        }
262
263
        $modifiedKeyword->created_at = $keyword['CreatedAt'];
264
265
        $modifiedKeyword->ranking = new StatKeywordRanking([
266
            'date' => $keyword['Ranking']['date'],
267
            'type' => $keyword['Ranking']['type']
268
        ]);
269
270 View Code Duplication
        if(array_key_exists('Google', $keyword['Ranking'])){
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...
271
            $modifiedKeyword->ranking->google = $this->analyzeRanking($keyword['Ranking']['Google'], $keyword['Ranking']['type']);
272
        }
273
274 View Code Duplication
        if(array_key_exists('Yahoo', $keyword['Ranking'])){
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...
275
            $modifiedKeyword->ranking->yahoo = $this->analyzeRanking($keyword['Ranking']['Yahoo'], $keyword['Ranking']['type']);
276
        }
277
278 View Code Duplication
        if(array_key_exists('Bing', $keyword['Ranking'])){
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...
279
            $modifiedKeyword->ranking->bing = $this->analyzeRanking($keyword['Ranking']['Bing'], $keyword['Ranking']['type']);
280
        }
281
282
        return $modifiedKeyword;
283
    }
284
285
    private function analyzeRanking($rankingForEngine, $rankingType)
286
    {
287
        if($rankingType == 'highest') {
288
            return $this->transformRanking($rankingForEngine);
289
        }
290
291
        if(is_null($rankingForEngine['Result'])){
292
            return null;
293
        }
294
295
        $rankings = $this->getCollection($rankingForEngine['Result'], 'Rank');
296
297
        $rankings->transform(function($ranking, $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...
298
            return $this->transformRanking($ranking);
299
        });
300
301
        return $rankings;
302
303
    }
304
305
    private function transformRanking($ranking)
306
    {
307
        $transformedRanking = new StatKeywordEngineRanking();
308
        $transformedRanking->rank = $ranking['Rank'];
309
        if(array_key_exists('BaseRank', $ranking)){
310
            $transformedRanking->base_rank = $ranking['BaseRank'];
311
        }
312
        $transformedRanking->url = $ranking['Url'];
313
314
        return $transformedRanking;
315
    }
316
317
    private function transformTag($tag)
318
    {
319
        $modifiedTag = new StatTag();
320
        $modifiedTag->id = $tag['Id'];
321
        $modifiedTag->tag = $tag['Tag'];
322
323
        if(isset($tag['RankDistribution'])){
324
            $modifiedTag->rank_distribution = $this->transformRankDistribution($tag['RankDistribution']);
325
        } else {
326
            $modifiedTag->rank_distribution = null;
327
        }
328
329
        return $modifiedTag;
330
    }
331
332
}
333