Completed
Push — master ( 898373...fb0bef )
by Nicolaas
04:30
created

ComputedLanguageAndCountryCode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
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 defaulf country.
155
     *
156
     * @return EcommerceCountry
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 defaulf 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)  $countryCodeOrObject
195
     * @return EcommerceCountry
196
     */
197
    public static function get_real_country($country = null)
198
    {
199
        if ($country && (! is_object($country))) {
200
            if (isset(self::$_get_real_country_cache[$country])) {
201
                return self::$_get_real_country_cache[$country];
202
            } else {
203
                $originalCode = $country;
204
            }
205
        }
206
        $order = ShoppingCart::current_order();
207
        if (! $country) {
208
            $country = $order->getCountry();
209
        }
210
        if (! $country) {
211
            $country = EcommerceCountry::get_country();
212
        }
213
        if ($country instanceof EcommerceCountry) {
214
            $type = "object";
0 ignored issues
show
Unused Code introduced by
$type 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...
215
            //do nothing
216
        } elseif (is_numeric($country) && intval($country) == $country) {
217
            $type = "number";
0 ignored issues
show
Unused Code introduced by
$type 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...
218
            $country = EcommerceCountry::get()->byID($country);
219
        } elseif (is_string($country)) {
220
            $type = "string";
0 ignored issues
show
Unused Code introduced by
$type 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...
221
            $country = strtoupper($country);
222
            $country = EcommerceCountry::get_country_object(false, $country);
223
        }
224
        if ($country && $country instanceof EcommerceCountry) {
225
            if ($country->AlwaysTheSameAsID) {
226
                $realCountry = $country->AlwaysTheSameAs();
227
                if ($realCountry && $realCountry->exists()) {
228
                    $country = $realCountry;
229
                }
230
            }
231
        }
232
        if (! $country instanceof EcommerceCountry) {
233
            user_error('No country could be found');
234
        }
235
        if (!empty($originalCode)) {
236
            self::$_get_real_country_cache[$originalCode] = $country;
237
        }
238
        return $country;
239
    }
240
    /**
241
     *
242
     * @return EcommerceCountry
243
     */
244
    public static function get_backup_country()
245
    {
246
        $obj = EcommerceCountry::get()->filter(array("IsBackupCountry" => true))->first();
247
        if (! $obj) {
248
            $obj = EcommerceCountry::get()->filter(array("Code" => EcommerceConfig::get('EcommerceCountry', 'default_country_code')))->first();
249
            if (! $obj) {
250
                $obj = EcommerceCountry::get()->first();
251
            }
252
        }
253
        return $obj;
254
    }
255
256
257
    /**
258
     *
259
     *
260
     * @return boolean
261
     */
262
    public function hasDistributor()
263
    {
264
        $countryObject = CountryPrice_EcommerceCountry::get_real_country($this->owner);
265
266
        return
267
            $countryObject->DistributorID &&
268
            $countryObject->Distributor() &&
269
            $countryObject->Distributor()->exists();
270
    }
271
272
273
    /**
274
     * make sure there is always a backup country ...
275
     */
276
    public function requireDefaultRecords()
277
    {
278
        $backupCountry = EcommerceCountry::get()->filter(array("IsBackupCountry" => 1))->first();
279
        if (!$backupCountry) {
280
            $backupCountry = self::get_backup_country();
281
            if ($backupCountry) {
282
                $backupCountry->IsBackupCountry = true;
283
                $backupCountry->write();
284
            }
285
        }
286
        if ($backupCountry) {
287
            DB::query("UPDATE EcommerceCountry SET IsBackupCountry = 0 WHERE EcommerceCountry.ID <> ".$backupCountry->ID);
288
            DB::alteration_message("Creating back-up country");
289
        } else {
290
            DB::alteration_message("Back-up country has not been set", "deleted");
291
        }
292
    }
293
294
    /**
295
     * @return string
296
     */
297
    public function ComputedLanguageAndCountryCode()
298
    {
299
        if($this->owner->LanguageAndCountryCode) {
300
            return $this->owner->LanguageAndCountryCode;
301
        }
302
        return strtolower('en-'.$this->owner->Code);
303
    }
304
}
305