findNewURL()   F
last analyzed

Complexity

Conditions 14
Paths 330

Size

Total Lines 66

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 3.8083
c 0
b 0
f 0
cc 14
nc 330
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 *
5
 * Common use:
6
 * ```php
7
 *    CountryPrices_ChangeCountryController::changeto('XX');
8
 *    CountryPrices_ChangeCountryController::new_country_link('XX');
9
 * ```
10
 *
11
 */
12
13
class CountryPrices_ChangeCountryController extends ContentController
14
{
15
16
17
    /**
18
     * make sure to match route...
19
     * @var string
20
     */
21
    private static $url_segment = 'shoppingcart-countries';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
22
23
    /**
24
     * needs to be saved like this:
25
     * ZA => 'myshop.co.za'
26
     *
27
     * @var array
28
     */
29
    private static $off_site_url_redirects = array();
30
31
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
32
        "changeto" => true,
33
        "confirmredirection" => true
34
    );
35
36
    /**
37
     * only call this function if it is a NEW country we are dealing with!
38
     *
39
     * without force it is a halfway house.
40
     *
41
     * @param string  $newCountryCode
42
     * @param bool    $force
43
     *
44
     */
45
    public static function set_new_country($newCountryCode, $force = true)
46
    {
47
        $newCountryCode = strtoupper($newCountryCode);
48
        $o = Shoppingcart::current_order();
49
        if ($o && $o->exists()) {
50
            $orderCountry = $o->getCountry();
51
            if ($orderCountry === $newCountryCode || CountryPrice_EcommerceCountry::countries_belong_to_same_group($orderCountry, $newCountryCode)) {
52
                //nothing to see here, please move on!
53
                return;
54
            }
55
            ShoppingCart::singleton()->clear();
56
        }
57
58
        Session::set('MyCloudFlareCountry', $newCountryCode);
59
        CountryPrice_OrderDOD::localise_order($newCountryCode, $force, $runAgain = true);
60
    }
61
62
    /**
63
     * link to change to a new country.
64
     *
65
     * @param string $newCountryCode
66
     *
67
     */
68
    public static function new_country_link($newCountryCode)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
69
    {
70
        $newCountryCode = strtoupper($newCountryCode);
71
        $redirectsArray = Config::inst()->get('CountryPrices_ChangeCountryController', 'off_site_url_redirects');
72
        if (isset($redirectsArray[$newCountryCode])) {
73
            return $redirectsArray[$newCountryCode];
74
        }
75
76
        return Injector::inst()->get('CountryPrices_ChangeCountryController')->Link('changeto/'.strtolower($newCountryCode));
77
    }
78
79
    /**
80
     *
81
     * @param  SS_HTTPRequest $request
82
     *
83
     * @return SS_HTTPResponse
0 ignored issues
show
Documentation introduced by
Should the return type not be SS_HTTPResponse|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
84
     */
85
    public function changeto($request)
86
    {
87
        //check for offsite redirects???
88
        $newCountryCode = Convert::raw2sql(strtoupper($request->param('ID')));
89
        self::set_new_country($newCountryCode);
0 ignored issues
show
Bug introduced by
It seems like $newCountryCode defined by \Convert::raw2sql(strtou...$request->param('ID'))) on line 88 can also be of type array; however, CountryPrices_ChangeCoun...ller::set_new_country() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
90
91
        //redirect now
92
        if (isset($_GET['force']) && $_GET['force']) {
93
            return $this->redirect($this->Link($newCountryCode) . '?force-back-home');
94
        }
95
        if (isset($_GET['force-back-home']) && $_GET['force-back-home']) {
96
            return $this->redirect(Director::baseURL('/'));
0 ignored issues
show
Unused Code introduced by
The call to Director::baseURL() has too many arguments starting with '/'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
97
        }
98
99
        $newLink = $this->findNewURL($newCountryCode);
0 ignored issues
show
Bug introduced by
It seems like $newCountryCode defined by \Convert::raw2sql(strtou...$request->param('ID'))) on line 88 can also be of type array; however, CountryPrices_ChangeCoun...ontroller::findNewURL() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
100
        if ($newLink) {
101
            return $this->redirect($newLink);
102
        }
103
104
        return [];
105
    }
106
107
    public function Link($action = null)
108
    {
109
        $link = Controller::join_links(
110
            Config::inst()->get('CountryPrices_ChangeCountryController', 'url_segment'),
111
            $action
112
        );
113
114
        return $link . '/';
115
    }
116
117
    /**
118
     * Remove a query string parameter from an URL.
119
     *
120
     * @param string $newCountryCode
121
     *
122
     * @return string
123
     */
124
    public function findNewURL($newCountryCode)
125
    {
126
127
        //COPIED FROM DIRECTOR::redirectBack()
128
        // Don't cache the redirect back ever
129
        HTTP::set_cache_age(0);
130
131
        $url = null;
132
133
        // In edge-cases, this will be called outside of a handleRequest() context; in that case,
134
        // redirect to the homepage - don't break into the global state at this stage because we'll
135
        // be calling from a test context or something else where the global state is inappropraite
136
        if ($this->getRequest()) {
137
            if ($this->getRequest()->requestVar('BackURL')) {
138
                $url = $this->getRequest()->requestVar('BackURL');
139
            } elseif ($this->getRequest()->isAjax() && $this->getRequest()->getHeader('X-Backurl')) {
140
                $url = $this->getRequest()->getHeader('X-Backurl');
141
            } elseif ($this->getRequest()->getHeader('Referer')) {
142
                $url = $this->getRequest()->getHeader('Referer');
143
            }
144
        }
145
146
        if (!$url) {
147
            $url = Director::baseURL();
148
        }
149
150
        // absolute redirection URLs not located on this site may cause phishing
151
        if (Director::is_site_url($url)) {
152
            $oldURL = Director::absoluteURL($url, true);
153
            $parsedUrl = parse_url($oldURL);
154
            $query = array();
155
156
            if (isset($parsedUrl['query'])) {
157
                $varname = $this->Config()->get('locale_get_parameter');
158
                parse_str($parsedUrl['query'], $query);
159
                if (isset($query[$varname])) {
160
                    if ($query[$varname] !== $newCountryCode) {
161
                        unset($query[$varname]);
162
                    }
163
                }
164
            }
165
166
            $path = isset($parsedUrl['path']) ? $parsedUrl['path'] : '';
0 ignored issues
show
Unused Code introduced by
$path is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
167
168
            $query = empty($query) ? '' :  '?'. http_build_query($query);
169
            $newURL =
170
                $parsedUrl['scheme'] .
171
                '://' .
172
                Controller::join_links(
173
                    $parsedUrl['host'],
174
                    $parsedUrl['path']
175
                ).
176
                $query;
177
            $newURLwithNewCountryCode = CountryPrice_Translation::get_country_url_provider()
0 ignored issues
show
Bug introduced by
The method replaceCountryCodeInUrl cannot be called on \CountryPrice_Translatio..._country_url_provider() (of type string).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
178
                ->replaceCountryCodeInUrl(
179
                    $newCountryCode,
180
                    $newURL
181
                );
182
            if ($newURLwithNewCountryCode) {
183
                return $newURLwithNewCountryCode;
184
            } else {
185
                return $newURL;
186
            }
187
        }
188
        return '/';
189
    }
190
191
    public function confirmredirection($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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
    {
193
    }
194
}
195