SemRush   B
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 228
Duplicated Lines 10.09 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95.31%

Importance

Changes 14
Bugs 1 Features 5
Metric Value
wmc 40
c 14
b 1
f 5
lcom 1
cbo 4
dl 23
loc 228
ccs 122
cts 128
cp 0.9531
rs 8.2608

20 Methods

Rating   Name   Duplication   Size   Complexity  
A getDomainRank() 0 6 2
A getDomainRankHistory() 0 6 2
A getOrganicKeywords() 0 4 1
A getCompetitors() 0 4 1
A getDomainGraph() 0 17 2
A getApiData() 0 5 1
A getSemRushDatabase() 0 6 2
A guardDomainIsValid() 0 6 2
A guardDatabaseIsValid() 0 6 2
B guardValidArgsForGetDomainGraph() 0 18 8
A getBackendData() 0 15 4
A getBackendUrl() 8 8 1
A getWidgetUrl() 8 8 1
A getWidgetData() 0 8 3
A checkDatabase() 0 4 2
A getValidDatabase() 0 8 1
A getDBs() 0 16 1
B getParams() 0 31 1
A exc() 7 7 2
A getDomainFromUrl() 0 8 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like SemRush often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use SemRush, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace SEOstats\Services;
3
4
/**
5
 * SEOstats extension for SEMRush data.
6
 *
7
 * @package    SEOstats
8
 * @author     Stephan Schmitz <[email protected]>
9
 * @copyright  Copyright (c) 2010 - present Stephan Schmitz
10
 * @license    http://eyecatchup.mit-license.org/  MIT License
11
 * @updated    2013/08/14
12
 */
13
14
use SEOstats\Common\SEOstatsException as E;
15
use SEOstats\SEOstats as SEOstats;
16
use SEOstats\Config as Config;
17
use SEOstats\Helper as Helper;
18
19
class SemRush extends SEOstats
20
{
21 30
    public static function getDBs()
22
    {
23
        return array(
24 30
            "au",     # Google.com.au (Australia)
25 30
            "br",     # Google.com.br (Brazil)
26 30
            "ca",     # Google.ca (Canada)
27 30
            "de",     # Google.de (Germany)
28 30
            "es",     # Google.es (Spain)
29 30
            "fr",     # Google.fr (France)
30 30
            "it",     # Google.it (Italy)
31 30
            "ru",     # Google.ru (Russia)
32 30
            "uk",     # Google.co.uk (United Kingdom)
33 30
            'us',     # Google.com (United States)
34
            "us.bing" # Bing.com
35 30
        );
36
    }
37
38 1
    public static function getParams()
39
    {
40
        return array(
41
          "DomainReports" => array(
42 1
            "Ac" => "Estimated expenses the site has for advertising in Ads (per month).",
43 1
            "Ad" => "Number of Keywords this site has in the TOP20 Ads results.",
44 1
            "At" => "Estimated number of visitors coming from Ads (per month).",
45 1
            "Dn" => "The requested site name.",
46 1
            "Dt" => "The date when the report data was computed (formatted as YYYYmmdd).",
47 1
            "Np" => "The number of keywords for which the site is displayed in search results next to the analyzed site.",
48 1
            "Oa" => "Estimated number of potential ad/traffic buyers.",
49 1
            "Oc" => "Estimated cost of purchasing the same number of visitors through Ads.",
50 1
            "Oo" => "Estimated number of competitors in organic search.",
51 1
            "Or" => "Number of Keywords this site has in the TOP20 organic results.",
52 1
            "Ot" => "Estimated number of visitors coming from the first 20 search results (per month).",
53
            "Rk" => "The SEMRush Rank (rating of sites by the number of visitors coming from the first 20 search results)."
54 1
          ),
55
          "OrganicKeywordReports" => array(
56 1
            "Co" => "Competition of advertisers for that term (the higher the number - the greater the competition).",
57 1
            "Cp" => "Average price of a click on an Ad for this search query (in U.S. dollars).",
58 1
            "Nr" => "The number of search results - how many results does the search engine return for this query.",
59 1
            "Nq" => "Average number of queries for the keyword per month (for the corresponding local version of search engine).",
60 1
            "Ph" => "The search query the site has within the first 20 search results.",
61 1
            "Po" => "The site&#39;s position for the search query (at the moment of data collection).",
62 1
            "Pp" => "The site&#39;s position for the search query (at the time of prior data collection).",
63 1
            "Tc" => "The estimated value of the organic traffic generated by the query as compared to the cost of purchasing the same volume of traffic through Ads.",
64 1
            "Tr" => "The ratio comparing the number of visitors coming to the site from this search request to all visitors to the site from search results.",
65
            "Ur" => "URL of a page on the site displayed in search results for this query (landing page)."
66 1
          )
67 1
        );
68
    }
69
70
    /**
71
     * Returns the SEMRush main report data.
72
     * (Only main report is public available.)
73
     *
74
     * @access       public
75
     * @param   url  string             Domain name only, eg. "ebay.com" (/wo quotes).
76
     * @param   db   string             Optional: The database to use. Valid values are:
77
     *                                  au, br, ca, de, es, fr, it, ru, uk, us, us.bing (us is default)
78
     * @return       array              Returns an array containing the main report data.
79
     * @link         http://www.semrush.com/api.html
80
     */
81 6
    public static function getDomainRank($url = false, $db = false)
82
    {
83 6
        $data = self::getBackendData($url, $db, 'domain_rank');
84
85 4
        return is_array($data) ? $data['rank']['data'][0] : $data;
86
    }
87
88 6
    public static function getDomainRankHistory($url = false, $db = false)
89
    {
90 6
        $data = self::getBackendData($url, $db, 'domain_rank_history');
91
92 4
        return is_array($data) ? $data['rank_history'] : $data;
93
    }
94
95 4
    public static function getOrganicKeywords($url = false, $db = false)
96
    {
97 4
        return static::getWidgetData($url, $db, 'organic', 'organic');
98
    }
99
100 4
    public static function getCompetitors($url = false, $db = false)
101
    {
102 4
        return static::getWidgetData($url, $db, 'organic_organic', 'organic_organic');
103
    }
104
105 10
    public static function getDomainGraph($reportType = 1, $url = false, $db = false, $w = 400, $h = 300, $lc = 'e43011', $dc = 'e43011', $lang = 'en', $html = true)
106
    {
107 10
        $domain = static::getDomainFromUrl($url);
108 9
        $database = static::getValidDatabase($db);
109
110 8
        static::guardValidArgsForGetDomainGraph($reportType, $w, $h, $lang);
111
112 2
        $imgUrl = sprintf(Config\Services::SEMRUSH_GRAPH_URL,
113 2
            $domain, $database, $reportType, $w, $h, $lc, $dc, $lang);
114
115 2
        if (! $html) {
116 1
            return $imgUrl;
117
        } else {
118 1
            $imgTag = '<img src="%s" width="%s" height="%s" alt="SEMRush Domain Trend Graph for %s"/>';
119 1
            return sprintf($imgTag, $imgUrl, $w, $h, $domain);
120
        }
121
    }
122
123 13
    protected static function getApiData($url)
124
    {
125 13
        $json = static::_getPage($url);
126 13
        return Helper\Json::decode($json, true);
127
    }
128
129 29
    protected static function getSemRushDatabase($db)
130
    {
131 29
        return false !== $db
132 29
            ? $db
133 29
            : Config\DefaultSettings::SEMRUSH_DB;
134
    }
135
136 36
    protected static function guardDomainIsValid($domain)
137
    {
138 36
        if (false == $domain) {
139 7
            self::exc('Invalid domain name.');
140
        }
141 29
    }
142
143 29
    protected static function guardDatabaseIsValid($database)
144
    {
145 29
        if (false === $database) {
146 7
            self::exc('db');
147
        }
148 22
    }
149
150 8
    protected static function guardValidArgsForGetDomainGraph($reportType, $width, $height, $lang)
151
    {
152 8
        if ($reportType > 5 || $reportType < 1) {
153 1
            self::exc('Report type must be between 1 (one) and 5 (five).');
154
        }
155
156 7
        if ($width > 400 || $width < 200) {
157 2
            self::exc('Image width must be between 200 and 400 px.');
158
        }
159
160 5
        if ($height > 300 || $height < 150) {
161 2
            self::exc('Image height must be between 150 and 300 px.');
162
        }
163
164 3
        if (strlen($lang) != 2) {
165 1
            self::exc('You must specify a valid language code.');
166
        }
167 2
    }
168
169 12
    protected static function getBackendData($url, $db, $reportType)
170
    {
171 12
        $db      = false !== $db ? $db : Config\DefaultSettings::SEMRUSH_DB;
172 12
        $dataUrl = self::getBackendUrl($url, $db, $reportType);
173 8
        $data    = self::getApiData($dataUrl);
174
175 8
        if (!is_array($data)) {
176 6
            $data = self::getApiData(str_replace('.backend.', '.api.', $dataUrl));
177 6
            if (!is_array($data)) {
178 4
                return parent::noDataDefaultValue();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (noDataDefaultValue() instead of getBackendData()). Are you sure this is correct? If so, you might want to change this to $this->noDataDefaultValue().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
179
            }
180 2
        }
181
182 4
        return $data;
183
    }
184
185 15 View Code Duplication
    protected static function getBackendUrl($url, $db, $reportType)
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...
186
    {
187 15
        $domain = static::getDomainFromUrl($url);
188 12
        $database = static::getValidDatabase($db);
189
190 9
        $backendUrl = Config\Services::SEMRUSH_BE_URL;
191 9
        return sprintf($backendUrl, $database, $reportType, $domain);
192
    }
193
194 11 View Code Duplication
    protected static function getWidgetUrl($url, $db, $reportType)
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...
195
    {
196 11
        $domain = static::getDomainFromUrl($url);
197 8
        $database = static::getValidDatabase($db);
198
199 5
        $widgetUrl = Config\Services::SEMRUSH_WIDGET_URL;
200 5
        return sprintf($widgetUrl, $reportType, $database, $domain);
201
    }
202
203 8
    protected static function getWidgetData($url, $db, $reportType, $valueKey)
204
    {
205 8
        $db      = false !== $db ? $db : Config\DefaultSettings::SEMRUSH_DB;
206 8
        $dataUrl = self::getWidgetUrl($url, $db, $reportType);
207 4
        $data    = self::getApiData($dataUrl);
208
209 4
        return !is_array($data) ? parent::noDataDefaultValue() : $data[ $valueKey ];
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (noDataDefaultValue() instead of getWidgetData()). Are you sure this is correct? If so, you might want to change this to $this->noDataDefaultValue().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
210
    }
211
212 29
    protected static function checkDatabase($db)
213
    {
214 29
        return !in_array($db, self::getDBs()) ? false : $db;
215
    }
216
217
    /**
218
     *
219
     * @throws E
220
     */
221 20 View Code Duplication
    protected static function exc($err)
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...
222
    {
223 20
        $e = ($err == 'db') ? "Invalid database. Choose one of: " .
224 20
            substr( implode(", ", self::getDBs()), 0, -2) : $err;
225 20
        throw new E($e);
226
        exit(0);
0 ignored issues
show
Unused Code introduced by
die(0); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
227
    }
228
229 36
    protected static function getDomainFromUrl($url)
230
    {
231 36
        $url      = parent::getUrl($url);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (getUrl() instead of getDomainFromUrl()). Are you sure this is correct? If so, you might want to change this to $this->getUrl().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
232 36
        $domain   = Helper\Url::parseHost($url);
233 36
        static::guardDomainIsValid($domain);
234
235 29
        return $domain;
236
    }
237
238 29
    protected static function getValidDatabase($db)
239
    {
240 29
        $db = self::getSemRushDatabase($db);
241 29
        $database = self::checkDatabase($db);
242 29
        static::guardDatabaseIsValid($database);
243
244 22
        return $database;
245
    }
246
}
247