Issues (33)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/Api/StatBulk.php (12 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace SchulzeFelix\Stat\Api;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Arr;
7
use SchulzeFelix\Stat\Exceptions\ApiException;
8
use SchulzeFelix\Stat\Objects\StatBulkJob;
9
use SchulzeFelix\Stat\Objects\StatKeyword;
10
use SchulzeFelix\Stat\Objects\StatKeywordEngineRanking;
11
use SchulzeFelix\Stat\Objects\StatKeywordRanking;
12
use SchulzeFelix\Stat\Objects\StatKeywordStats;
13
use SchulzeFelix\Stat\Objects\StatLocalSearchTrend;
14
use SchulzeFelix\Stat\Objects\StatProject;
15
use SchulzeFelix\Stat\Objects\StatSite;
16
use SchulzeFelix\Stat\Objects\StatTag;
17
18
class StatBulk extends BaseStat
19
{
20
    public function list()
21
    {
22
        $response = $this->performQuery('bulk/list');
23
24
        $bulkJobs = collect();
25
26
        if ($response['resultsreturned'] == 0) {
27
            return $bulkJobs;
28
        }
29
30
        if ($response['resultsreturned'] == 1) {
31
            $bulkJobs->push($response['Result']);
32
        }
33
34
        if ($response['resultsreturned'] > 1) {
35
            $bulkJobs = collect($response['Result']);
36
        }
37
38
        return $bulkJobs->transform(function ($job, $key) {
0 ignored issues
show
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...
39
            return $this->transformBulkJobStatus($job);
40
        });
41
    }
42
43
    /**
44
     * Schedule the creation of a new bulk export job for ranks.
45
     *
46
     * @param Carbon $date Note that you cannot create bulk jobs for the current date or dates in the future.
47
     * @param array|null $sites If no site IDs are passed in, ranks are reported for all sites in the system on the given date.
48
     * @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'.
49
     * @param array|null $engines This parameter lets you choose which search engines to include in the export, defaulting to Google and Bing. Engines can be passed in a array to get multiple. ['google', 'bing']
50
     * @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.
51
     * @param bool $crawledKeywordsOnly This parameter causes the API to only include output for keywords that were crawled on the date parameter provided.
52
     * @return int
53
     */
54
    public function ranks(Carbon $date, array $sites = null, $rankType = 'highest', $engines = null, bool $currentlyTrackedOnly = false, bool $crawledKeywordsOnly = false)
55
    {
56
        $this->validateBulkDate($date);
57
58
        $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...
59
        $arguments['rank_type'] = $rankType;
60
        $arguments['currently_tracked_only'] = $currentlyTrackedOnly;
61
        $arguments['crawled_keywords_only'] = $crawledKeywordsOnly;
62
63
        if (! is_null($sites) && count($sites) > 0) {
64
            $arguments['site_id'] = implode(',', $sites);
65
        }
66
        if (! is_null($engines) && count($engines) > 0) {
67
            $arguments['engines'] = implode(',', $engines);
68
        }
69
        $response = $this->performQuery('bulk/ranks', $arguments);
70
71
        return (int) $response['Result']['Id'];
72
    }
73
74
    public function status($bulkJobID)
75
    {
76
        $response = $this->performQuery('bulk/status', ['id' => $bulkJobID]);
77
78
        return $this->transformBulkJobStatus($response['Result']);
79
    }
80
81
    public function delete($bulkJobID)
82
    {
83
        $response = $this->performQuery('bulk/delete', ['id' => $bulkJobID]);
84
85
        return (int) $response['Result']['Id'];
86
    }
87
88 View Code Duplication
    public function siteRankingDistributions($date)
89
    {
90
        $this->validateBulkDate($date);
91
92
        $response = $this->performQuery('bulk/site_ranking_distributions', ['date' => $date->toDateString()]);
93
94
        return (int) $response['Result']['Id'];
95
    }
96
97 View Code Duplication
    public function tagRankingDistributions($date)
98
    {
99
        $this->validateBulkDate($date);
100
101
        $response = $this->performQuery('bulk/tag_ranking_distributions', ['date' => $date->toDateString()]);
102
103
        return (int) $response['Result']['Id'];
104
    }
105
106
    public function get($bulkJobID)
107
    {
108
        $bulkStatus = $this->status($bulkJobID);
109
110
        if ($bulkStatus['status'] != 'Completed') {
111
            throw ApiException::resultError('Bulk Job is not completed. Current status: '.$bulkJobID['status'].'.');
112
        }
113
114
        $bulkStream = $this->statClient->downloadBulkJobStream($bulkStatus['stream_url']);
115
116
        return $this->parseBulkJob($bulkStream['Response']);
117
    }
118
119
    /**
120
     * @param Carbon $date
121
     * @throws ApiException
122
     */
123
    private function validateBulkDate(Carbon $date)
124
    {
125
        if ($date->isSameDay(Carbon::now()) or $date->isFuture()) {
126
            throw ApiException::resultError('You cannot create bulk jobs for the current date or dates in the future.');
127
        }
128
    }
129
130
    private function parseBulkJob($bulkStream)
131
    {
132
        $projects = $this->getCollection($bulkStream['Project']);
133
134
        $projects->transform(function ($project, $key) {
0 ignored issues
show
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...
135
            return $this->transformProject($project);
136
        });
137
138
        return $projects;
139
    }
140
141
    private function transformProject($project)
142
    {
143
        $transformedProject = new StatProject();
144
        $transformedProject->id = $project['Id'];
145
        $transformedProject->name = $project['Name'];
146
        $transformedProject->total_sites = $project['TotalSites'];
147
        $transformedProject->created_at = $project['CreatedAt'];
148
149
        if ($project['TotalSites'] == 0) {
150
            $transformedProject->sites = collect();
151
        }
152
        if ($project['TotalSites'] == 1) {
153
            $transformedProject->sites = collect([$project['Site']]);
154
        }
155
        if ($project['TotalSites'] > 1) {
156
            $transformedProject->sites = collect($project['Site']);
157
        }
158
        $transformedProject->sites->transform(function ($site, $key) {
0 ignored issues
show
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...
159
            return $this->transformSite($site);
160
        });
161
162
        return $transformedProject;
163
    }
164
165
    private function transformSite($site)
166
    {
167
        $transformedSite = new StatSite();
168
        $transformedSite->id = $site['Id'];
169
        $transformedSite->url = $site['Url'];
170
        $transformedSite->total_keywords = $site['TotalKeywords'];
171
        $transformedSite->created_at = $site['CreatedAt'];
172
173
        if (array_key_exists('Keyword', $site)) {
174
            $transformedSite->keywords = collect($site['Keyword'])->transform(function ($keyword, $key) {
0 ignored issues
show
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...
175
                return $this->transformKeyword($keyword);
176
            });
177
        }
178
179
        if (array_key_exists('RankDistribution', $site)) {
180
            $transformedSite->rank_distribution = $this->transformRankDistribution($site['RankDistribution']);
181
        }
182
183
        if (array_key_exists('Tag', $site)) {
184
            $transformedSite->tags = $this->getCollection($site['Tag'])->transform(function ($tag, $key) {
0 ignored issues
show
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...
185
                return $this->transformTag($tag);
186
            });
187
        }
188
189
        return $transformedSite;
190
    }
191
192
    private function transformKeyword($keyword)
193
    {
194
        $modifiedKeyword = new StatKeyword();
195
        $modifiedKeyword->id = $keyword['Id'];
196
        $modifiedKeyword->keyword = $keyword['Keyword'];
197
        $modifiedKeyword->keyword_market = $keyword['KeywordMarket'];
198
        $modifiedKeyword->keyword_location = $keyword['KeywordLocation'];
199
        $modifiedKeyword->keyword_device = $keyword['KeywordDevice'];
200
        $modifiedKeyword->keyword_categories = $keyword['KeywordCategories'];
201
202 View Code Duplication
        if (is_null($keyword['KeywordTags'])) {
0 ignored issues
show
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...
203
            $modifiedKeyword->keyword_tags = collect();
204
        } else {
205
            $modifiedKeyword->keyword_tags = collect(explode(',', $keyword['KeywordTags']));
206
        }
207
208 View Code Duplication
        if (is_null($keyword['KeywordStats'])) {
0 ignored issues
show
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...
209
            $modifiedKeyword->keyword_stats = null;
210
        } else {
211
            $localTrends = collect($keyword['KeywordStats']['LocalSearchTrendsByMonth'])->map(function ($searchVolume, $month) {
212
                return new StatLocalSearchTrend([
213
                    'month' => strtolower($month),
214
                    'search_volume' => ($searchVolume == '-') ? null : $searchVolume,
215
                ]);
216
            });
217
218
            $modifiedKeyword->keyword_stats = new StatKeywordStats([
219
                'advertiser_competition' => $keyword['KeywordStats']['AdvertiserCompetition'],
220
                'global_search_volume' => $keyword['KeywordStats']['GlobalSearchVolume'],
221
                'targeted_search_volume' => $keyword['KeywordStats']['TargetedSearchVolume'],
222
                'cpc' => $keyword['KeywordStats']['CPC'],
223
                'local_search_trends_by_month' => $localTrends->values(),
224
            ]);
225
        }
226
227
        $modifiedKeyword->created_at = $keyword['CreatedAt'];
228
229
        $modifiedKeyword->ranking = new StatKeywordRanking([
230
            'date' => $keyword['Ranking']['date'],
231
            'type' => $keyword['Ranking']['type'],
232
        ]);
233
234 View Code Duplication
        if (array_key_exists('Google', $keyword['Ranking'])) {
0 ignored issues
show
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...
235
            $modifiedKeyword->ranking->google = $this->analyzeRanking($keyword['Ranking']['Google'], $keyword['Ranking']['type']);
236
        }
237
238 View Code Duplication
        if (array_key_exists('Bing', $keyword['Ranking'])) {
0 ignored issues
show
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->ranking->bing = $this->analyzeRanking($keyword['Ranking']['Bing'], $keyword['Ranking']['type']);
240
        }
241
242
        return $modifiedKeyword;
243
    }
244
245
    private function analyzeRanking($rankingForEngine, $rankingType)
246
    {
247
        if ($rankingType == 'highest') {
248
            return $this->transformRanking($rankingForEngine);
249
        }
250
251
        if (empty($rankingForEngine) || is_null($rankingForEngine['Result'])) {
252
            return;
253
        }
254
255
        $rankings = $this->getCollection($rankingForEngine['Result'], 'Rank');
256
257
        $rankings->transform(function ($ranking, $key) {
0 ignored issues
show
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...
258
            return $this->transformRanking($ranking);
259
        });
260
261
        return $rankings;
262
    }
263
264
    private function transformRanking($ranking)
265
    {
266
        $transformedRanking = new StatKeywordEngineRanking();
267
        $transformedRanking->rank = $ranking['Rank'];
268
        if (array_key_exists('BaseRank', $ranking)) {
269
            $transformedRanking->base_rank = $ranking['BaseRank'];
270
        }
271
        $transformedRanking->url = $ranking['Url'];
272
273
        return $transformedRanking;
274
    }
275
276
    private function transformTag($tag)
277
    {
278
        $modifiedTag = new StatTag();
279
        $modifiedTag->id = $tag['Id'];
280
        $modifiedTag->tag = $tag['Tag'];
281
282
        if (isset($tag['RankDistribution'])) {
283
            $modifiedTag->rank_distribution = $this->transformRankDistribution($tag['RankDistribution']);
284
        } else {
285
            $modifiedTag->rank_distribution = null;
286
        }
287
288
        return $modifiedTag;
289
    }
290
291
    private function transformBulkJobStatus($job)
292
    {
293
        $bulkJob = new StatBulkJob();
294
        $bulkJob->id = $job['Id'];
295
        $bulkJob->job_type = $job['JobType'];
296
        $bulkJob->format = $job['Format'];
297
298
        if (Arr::has($job, ['Project', 'Folder', 'SiteTitle', 'SiteUrl'])) {
299
            $bulkJob->project = $job['Project'];
300
            $bulkJob->folder = $job['Folder'];
301
            $bulkJob->site_title = $job['SiteTitle'];
302
            $bulkJob->site_url = $job['SiteUrl'];
303
        }
304
305
        $bulkJob->date = $job['Date'];
306
307
        $bulkJob->sites = collect();
308
        if (Arr::has($job, 'SiteId')) {
309
            $bulkJob->sites = collect(explode(',', $job['SiteId']))
310
                ->transform(function ($site, $key) {
0 ignored issues
show
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...
311
                    return (int) $site;
312
                });
313
        }
314
        $bulkJob->status = $job['Status'];
315
        $bulkJob->url = Arr::get($job, 'Url', null);
316
        $bulkJob->stream_url = Arr::get($job, 'StreamUrl', null);
317
        $bulkJob->created_at = $job['CreatedAt'];
318
319
        return $bulkJob;
320
    }
321
}
322