Passed
Push — master ( 2b3013...123071 )
by
unknown
02:55
created

countries_belong_to_same_group()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 21
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 7.1428
c 0
b 0
f 0
cc 8
eloc 13
nc 6
nop 2
1
<?php
2
3
/**
4
 * Adds fields to individual countries.
5
 *
6
 */
7
8
class CountryPrice_EcommerceCountry extends DataExtension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
9
{
10
    private static $db = array(
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
11
        'IsBackupCountry' => 'Boolean',
12
        'FAQContent' => 'HTMLText',
13
        'TopBarMessage' => 'Varchar(255)',
14
        'DeliveryCostNote' => 'Varchar(255)',
15
        'ShippingEstimation' => 'Varchar(255)',
16
        'ReturnInformation' => 'Varchar(255)',
17
        'ProductNotAvailableNote' => 'HTMLText',
18
        'LanguageAndCountryCode' => 'Varchar(20)'
19
    );
20
21
    private static $has_one = array(
0 ignored issues
show
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
22
        'Distributor' => 'Distributor',
23
        'EcommerceCurrency' => 'EcommerceCurrency',
24
        'AlwaysTheSameAs' => 'EcommerceCountry'
25
    );
26
27
    private static $has_many = array(
0 ignored issues
show
Unused Code introduced by
The property $has_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
28
        'ParentFor' => 'EcommerceCountry'
29
    );
30
31
    private static $searchable_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $searchable_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
32
        "AlwaysTheSameAsID" => true,
33
        "IsBackupCountry" => "ExactMatchFilter"
34
    );
35
36
    private static $default_sort = array(
0 ignored issues
show
Unused Code introduced by
The property $default_sort is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
37
        'Name' => 'DESC'
38
    );
39
40
41
    private static $indexes = array(
0 ignored issues
show
Unused Code introduced by
The property $indexes is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
42
        "IsBackupCountry" => true
43
    );
44
45
    private static $casting = array(
0 ignored issues
show
Unused Code introduced by
The property $casting is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
46
        "LanguageAndCountryCode" => 'Varchar'
47
    );
48
49
    public function updateCMSFields(FieldList $fields)
50
    {
51
        $fields->addFieldToTab(
52
            "Root.ParentCountry",
53
            DropdownField::create(
54
                'AlwaysTheSameAsID',
55
                'Parent Country',
56
                array('' => '--- PLEASE SELECT ---') + EcommerceCountry::get()->filter(array("AlwaysTheSameAsID" => 0))->exclude(array("ID" => $this->owner->ID))->map("ID", "Name")->toArray()
57
            )
58
        );
59
        if ($this->owner->AlwaysTheSameAsID) {
60
            $removeByNameArray = array(
61
                'IsBackupCountry',
62
                'DoNotAllowSales',
63
                'FAQContent',
64
                'TopBarMessage',
65
                'DeliveryCostNote',
66
                'ShippingEstimation',
67
                'ReturnInformation',
68
                'ProductNotAvailableNote',
69
                'DistributorID',
70
                'EcommerceCurrencyID',
71
                'ParentFor',
72
                'Regions'
73
            );
74
            foreach ($removeByNameArray as $removeByNameField) {
75
                $fields->removeByName(
76
                    $removeByNameField
77
                );
78
            }
79
        } else {
80
            $fields->addFieldToTab('Root.Messages', TextField::create('TopBarMessage', 'Top Bar Message')->setRightTitle("also see the site config for default messages"));
81
            if ($this->owner->DistributorID) {
82
                $FAQContentField = new HtmlEditorField('FAQContent', 'Content');
83
                $FAQContentField->setRows(7);
84
                $FAQContentField->setColumns(7);
85
                $fields->addFieldToTab('Root.FAQPage', $FAQContentField);
86
            } else {
87
                $fields->addFieldToTab(
88
                    'Root.FAQPage',
89
                    new LiteralField(
90
                        "FAQPageExplanation",
91
                        "<p class=\"message warning\">FAQ information can only be added to the main country for a ". _t('Distributor.SINGULAR_NAME', 'Distributor') ."</p>"
92
                    )
93
                );
94
            }
95
96
            $distributors = Distributor::get()
97
                ->filter(array("IsDefault" => 0));
98
            $distributors = $distributors->count() ? $distributors->map('ID', 'Name')->toArray() : array();
99
            $distributors = array('' => '--- PLEASE SELECT ---') + $distributors;
100
            $fields->addFieldToTab(
101
                'Root.Main',
102
                DropdownField::create('DistributorID', _t('Distributor.SINGULAR_NAME', 'Distributor'), array(0 => "-- Not Selected --") + $distributors),
103
                "DoNotAllowSales"
104
            );
105
106
            $fields->addFieldToTab(
107
                "Root.Testing",
108
                new LiteralField("LogInAsThisCountry", "<h3><a href=\"/whoami/setmycountry/".$this->owner->Code."/?countryfortestingonly=".$this->owner->Code."\">place an order as a person from ".$this->owner->Title."</a></h3>")
109
            );
110
111
            $fields->addFieldToTab(
112
                "Root.Currency",
113
                $fields->dataFieldByName("EcommerceCurrencyID")
114
            );
115
        }
116
    }
117
118
    public static function get_real_countries_list()
119
    {
120
        return EcommerceCountry::get()
121
            ->filter(array('DoNotAllowSales' => 0, 'AlwaysTheSameAsID' => 0));
122
    }
123
124
    /**
125
     *
126
     *
127
     * @param  [type] $countryCode [description]
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
128
     * @return DataList
129
     */
130
    public static function get_sibling_countries($countryCode = null)
131
    {
132
        $countryObject = self::get_real_country($countryCode);
133
        if ($countryObject->AlwaysTheSameAsID) {
134
            return EcommerceCountry::get()
135
                ->filterAny(
136
                    array(
137
                        'AlwaysTheSameAsID' => array($countryObject->AlwaysTheSameAsID),
138
                        "ID" => array($countryObject->AlwaysTheSameAsID, $countryObject->ID)
139
                    )
140
                );
141
        } else {
142
            return EcommerceCountry::get()
143
                ->filterAny(
144
                    array(
145
                        'AlwaysTheSameAsID' => $countryObject->ID,
146
                        'ID' => $countryObject->ID
147
                    )
148
                );
149
        }
150
    }
151
152
    /**
153
     * checks if the country has a distributor
154
     * and returns it.  If not, returns the default country.
155
     *
156
     * @return EcommerceCountry
0 ignored issues
show
Documentation introduced by
Should the return type not be EcommerceCountry|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...
157
     *
158
     */
159
    public static function get_distributor_country($countryCode = null)
160
    {
161
        $countryObject = CountryPrice_EcommerceCountry::get_real_country($countryCode);
162
        if ($countryObject && $countryObject->hasDistributor()) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
163
            //do nothing ...
164
        } else {
165
            $countryObject = self::get_backup_country();
166
        }
167
        return $countryObject;
168
    }
169
170
    /**
171
    * checks if the country has a distributor
172
    * and returns the primary country for the distributor.
173
    * If not, returns the default country.
174
     *
175
     * @return EcommerceCountry
176
     *
177
     */
178
    public static function get_distributor_primary_country($countryCode = null)
179
    {
180
        $countryObject = CountryPrice_EcommerceCountry::get_real_country($countryCode);
181
        if ($countryObject && $countryObject->hasDistributor()) {
182
            return $countryObject->Distributor()->PrimaryCountry();
183
        //do nothing ...
184
        } else {
185
            $countryObject = self::get_backup_country();
186
        }
187
        return $countryObject;
188
    }
189
190
    private static $_get_real_country_cache = array();
191
192
    /**
193
     * returns the 'always the same as' (parent) country if necessary
194
     * @param  EcommerceCountry | string | int   (optional)  $country
195
     *
196
     * @return EcommerceCountry
197
     */
198
    public static function get_real_country($country = null)
199
    {
200
        $country = EcommerceCountry::get_country_from_mixed_var($country);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
201
        if ($country) {
202
            $cacheKey = $country->Code;
203
        } elseif ($country) {
204
            $cacheKey = $country;
205
        } else {
206
            $cacheKey = 'notprovided';
207
        }
208
        if (isset(self::$_get_real_country_cache[$cacheKey]) && self::$_get_real_country_cache[$cacheKey]) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
209
        } else {
210
            //save original - just in case...
211
            $originalCountry = $country;
212
213
            //no country provided
214
            if (! $country) {
215
                $urlCountryCode = CountryPrice_Translation::get_country_url_provider()->CurrentCountrySegment();
0 ignored issues
show
Bug introduced by
The method CurrentCountrySegment 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...
216
217
                // 2. CHECK WHAT THE SYSTEM THINKS THE COUNTRY CHOULD BE
218
219
                //now we check it from order / session ....
220
                $order = ShoppingCart::current_order();
221
                if ($order && $order->exists()) {
222
                    Session::clear('temporary_country_order_store');
223
                    $countryCode = $order->getCountry();
224
                } else {
225
                    $countryCode = Session::get('temporary_country_order_store');
226
                }
227
228
                //if we still dont have a country then we use the standard e-commerce methods ...
229
                if (! $countryCode) {
230
                    $countryCode = EcommerceCountry::get_country();
231
                }
232
233
                //lets make our object!
234
                if ($countryCode) {
235
                    $country = DataObject::get_one('EcommerceCountry', ['Code' => $countryCode]);
236
                }
237
238
                $country = EcommerceCountry::get_country_from_mixed_var($country);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
239
                if ($country) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
240
                    //do nothing
241
                } else {
242
                    $country = null;
243
                }
244
                //IF THE COUNTRY DOES NOT MATCH THE URL COUNTRY THEN THE URL WINS!!!!
245
                if ($urlCountryCode) {
246
                    if (
247
                            ($country && $country->Code !== $urlCountryCode)
248
                        ||
249
                            ! $country
250
251
                    ) {
252
                        $country = DataObject::get_one('EcommerceCountry', ['Code' => $urlCountryCode]);
253
                        if ($country) {
254
                            //change country Object
255
                            //reset everything ...
256
                            CountryPrices_ChangeCountryController::set_new_country($country->Code);
257
                            // return self::get_real_country($country);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
258
                        } else {
259
                            return $this->redirect('404-country-not-found');
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The method redirect() does not seem to exist on object<CountryPrice_EcommerceCountry>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
260
                        }
261
                    } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
262
                    }
263
                }
264
            }
265
266
267
            //MAKE SURE WE HAVE AN OBJECT
268
            //get the Object
269
            $country = EcommerceCountry::get_country_from_mixed_var($country);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
270
271
272
            //LOOK FOR REPLACEMENT COUNTRIES
273
            //substitute (always the same as) check ....
274
            if ($country) {
275
                if ($country->AlwaysTheSameAsID) {
276
                    $realCountry = $country->AlwaysTheSameAs();
277
                    if ($realCountry && $realCountry->exists()) {
278
                        $country = $realCountry;
279
                    }
280
                }
281
            } else {
282
                //last chance ... do this only once ...
283
                $countryCode = EcommerceCountry::get_country_default();
284
                if ($countryCode && !$originalCountry) {
285
                    $country = self::get_real_country($countryCode);
286
                }
287
            }
288
289
            //FINAL BOARDING CALL!
290
            //surely we have one now???
291
            $country = EcommerceCountry::get_country_from_mixed_var($country);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
292
            if ($country) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
293
                //do nothing
294
            } else {
295
                //final backup....
296
                $country = EcommerceCountry::get()->first();
297
            }
298
299
            //set to cache ...
300
            self::$_get_real_country_cache[$cacheKey] = $country;
301
        }
302
303
        return self::$_get_real_country_cache[$cacheKey];
304
    }
305
306
    public static function countries_belong_to_same_group($countryOrCountryCodeA, $countryOrCountryCodeB)
307
    {
308
        $countryA = EcommerceCountry::get_country_from_mixed_var($countryOrCountryCodeA);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
309
        $countryB = EcommerceCountry::get_country_from_mixed_var($countryOrCountryCodeB);
0 ignored issues
show
Bug introduced by
The method get_country_from_mixed_var() does not exist on EcommerceCountry. Did you maybe mean get_country()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
310
        if($countryA && $countryB) {
311
            if($countryA->ID === $countryB->ID) {
312
                return true;
313
            }
314
            if($countryA->AlwaysTheSameAsID === $countryB->ID) {
315
                return true;
316
            }
317
            if($countryA->ID === $countryB->AlwaysTheSameAsID) {
318
                return true;
319
            }
320
            if($countryA->AlwaysTheSameAsID && $countryA->AlwaysTheSameAsID === $countryB->AlwaysTheSameAsID) {
321
                return true;
322
            }
323
        }
324
325
        return false;
326
    }
327
328
329
    /**
330
     *
331
     * @return EcommerceCountry
0 ignored issues
show
Documentation introduced by
Should the return type not be EcommerceCountry|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...
332
     */
333
    public static function get_backup_country()
334
    {
335
        $obj = EcommerceCountry::get()->filter(array("IsBackupCountry" => true))->first();
336
        if (! $obj) {
337
            $obj = EcommerceCountry::get()->filter(array("Code" => EcommerceConfig::get('EcommerceCountry', 'default_country_code')))->first();
338
            if (! $obj) {
339
                $obj = EcommerceCountry::get()->first();
340
            }
341
        }
342
        return $obj;
343
    }
344
345
346
    /**
347
     *
348
     *
349
     * @return boolean
350
     */
351
    public function hasDistributor()
352
    {
353
        $countryObject = CountryPrice_EcommerceCountry::get_real_country($this->owner);
354
355
        return
356
            $countryObject->DistributorID &&
357
            $countryObject->Distributor() &&
358
            $countryObject->Distributor()->exists();
359
    }
360
361
362
    /**
363
     * make sure there is always a backup country ...
364
     */
365
    public function requireDefaultRecords()
366
    {
367
        $backupCountry = EcommerceCountry::get()->filter(array("IsBackupCountry" => 1))->first();
368
        if (!$backupCountry) {
369
            $backupCountry = self::get_backup_country();
370
            if ($backupCountry) {
371
                $backupCountry->IsBackupCountry = true;
372
                $backupCountry->write();
373
            }
374
        }
375
        if ($backupCountry) {
376
            DB::query("UPDATE EcommerceCountry SET IsBackupCountry = 0 WHERE EcommerceCountry.ID <> ".$backupCountry->ID);
377
            DB::alteration_message("Creating back-up country");
378
        } else {
379
            DB::alteration_message("Back-up country has not been set", "deleted");
380
        }
381
    }
382
383
    /**
384
     * @return string
385
     */
386
    public function ComputedLanguageAndCountryCode()
387
    {
388
        if ($this->owner->LanguageAndCountryCode) {
389
            return $this->owner->LanguageAndCountryCode;
390
        }
391
        return strtolower('en-'.$this->owner->Code);
392
    }
393
}
394