CountryPrice_DistributorManagementTool::Products()   F
last analyzed

Complexity

Conditions 43
Paths 2

Size

Total Lines 230

Duplication

Lines 60
Ratio 26.09 %

Importance

Changes 0
Metric Value
dl 60
loc 230
rs 3.3333
c 0
b 0
f 0
cc 43
nc 2
nop 0

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
 * Controller that allows checking of all information.
5
 * @author Nicolaas @ sunnysideup .co .nz
6
 *
7
 *
8
 */
9
10
class CountryPrice_DistributorManagementTool extends Controller
11
{
12
    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...
13
        "setcountryprice" => 'distributors',
14
        "setobjectfield" => 'distributors'
15
    );
16
17
    /**
18
     * Holds the current distributor, if any
19
     *
20
     * @Var Distributor | Null
21
     */
22
    private $distributor = null;
23
24
    /**
25
     * List of Countries that the current member is allowed to see.
26
     * like so:
27
     * ID => Code
28
     * 1 => NZ
29
     *
30
     * @Var Array
31
     */
32
    private $countryArray = array();
33
34
    public function DistributorLabel()
35
    {
36
        return _t('Distributor.SINGULAR_NAME', 'Distributor');
37
    }
38
39
    /**
40
     * determine level of access
41
     */
42
    public function init()
43
    {
44
        parent::init();
45
        $member = Member::currentUser();
46
        $canViewAndEdit = false;
47
        $countries = null;
48
        if ($member) {
49
            if (Permission::check('ADMIN')) {
50
                $countries = CountryPrice_EcommerceCountry::get_real_countries_list()
51
                    ->exclude(array("DistributorID" => 0));
52
                $canViewAndEdit = true;
53
            } else {
54
                $distributor = $member->Distributor();
55
                if ($distributor->exists()) {
56
                    $this->distributor = $distributor;
57
                    $countries = $distributor->Countries();
58
                    $canViewAndEdit = true;
59
                }
60
                $primaryCountry = $distributor->PrimaryCountry();
61
                if ($primaryCountry && $primaryCountry->exists()) {
62
                    $distributorPrimaryCountryCode = $primaryCountry->Code;
63
                    $currentCountry = $countryObject = CountryPrice_EcommerceCountry::get_real_country();
0 ignored issues
show
Unused Code introduced by
$countryObject 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...
64
                    $currentCountryCode = '';
65
                    if ($currentCountry) {
66
                        $currentCountryCode = $currentCountry->Code;
67
                    }
68
                    if ($currentCountryCode !== $distributorPrimaryCountryCode) {
69
                        return $this->redirect(CountryPrices_ChangeCountryController::new_country_link($distributorPrimaryCountryCode));
70
                    }
71
                } else {
72
                    die("ERROR: No primary country has been set for this ".  _t('Distributor.SINGULAR_NAME', 'Distributor') .".");
73
                }
74
            }
75
            if ($countries && $countries->count()) {
76
                $this->countryArray = $countries->map("ID", "Code")->toArray();
77
            }
78
        }
79
        if (!$canViewAndEdit) {
80
            Security::permissionFailure($this, 'Please log in first or log in as a '. _t('Distributor.SINGULAR_NAME', 'Distributor'). '.');
81
        }
82
    }
83
84
    public function index($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...
85
    {
86
        return $this->renderWith('CountryPrice_DistributorManagementTool');
87
    }
88
89
90
91
    /********************
92
     * actions
93
     ********************/
94
95
    /**
96
     *
97
     *
98
     * NOT CURRENTLY IN USE!!!
99
     */
100
    public function setcountryprice()
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...
101
    {
102
        return "NOT IN USE";
103
        // 1) Check that all parameters have been specified
104
105
        $fields = $this->getCountryPriceIndexes();
0 ignored issues
show
Unused Code introduced by
$fields = $this->getCountryPriceIndexes(); 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...
106
        $fields['Price'] = 'Price';
107
108
        foreach ($fields as $field) {
109
            if (! isset($_REQUEST[$field])) {
110
                return "$field value missing";
111
            }
112
        }
113
114
        // 2 Check the parameters values
115
116
        $objectClass = $_REQUEST['ObjectClass'];
117
        $valid = false;
118
        if (class_exists($objectClass)) {
119
            $object = singleton($objectClass);
120
            if (is_a($object, 'DataObject') && $object->hasExtension('CountryPrice_BuyableExtension')) {
121
                $valid = true;
122
            }
123
        }
124
        if (! $valid) {
125
            return 'ObjectClass value incorrect';
126
        }
127
128
        $objectID = intval($_REQUEST['ObjectID']);
129
        $object = $objectClass::get()->byID($objectID);
130
        if (! $object) {
131
            return 'ObjectID value incorrect';
132
        }
133
134
        $country = strtoupper($_REQUEST['Country']);
135
        $countryObject = CountryPrice_EcommerceCountry::get_real_country(Convert::raw2sql($country));
136
        $countryCode = '';
137
        if ($countryObject) {
138
            $countryCode = $countryObject->Code;
139
        }
140
        $valid = false;
141
        $currencyPerCountry = CountryPrice_EcommerceCurrency::get_currency_per_country();
142
        if (isset($currencyPerCountry[$countryCode])) {
143
            $valid = true;
144
            if ($this->distributor) {
145
                $countries = $this->distributor->Countries()->map('Code', 'Code')->toArray();
0 ignored issues
show
Documentation Bug introduced by
The method Countries does not exist on object<Distributor>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
146
                if (! in_array($countryCode, $countries)) {
147
                    $valid = false;
148
                }
149
            }
150
        }
151
        if (! $valid) {
152
            return 'Country value incorrect';
153
        }
154
155
        $currency = strtoupper($_REQUEST['Currency']);
156
        if (strlen($currency) != 3) {
157
            return 'Currency value incorrect';
158
        }
159
160
        $price = $_REQUEST['Price'];
161
        if (! is_numeric($price)) {
162
            return 'Price value incorrect';
163
        }
164
165
        DB::query("
166
            INSERT INTO \"CountryPrice\"
167
                (\"Created\",\"LastEdited\",\"Price\",\"Country\",\"Currency\",\"ObjectClass\",\"ObjectID\")
168
            VALUES (NOW(),NOW(),$price,'$countryCode','$currency','$objectClass',$objectID)
169
            ON DUPLICATE KEY UPDATE \"LastEdited\" = VALUES(\"LastEdited\"), \"Price\" = VALUES(\"Price\")");
170
171
        return true;
172
    }
173
174
175
    /**
176
     *
177
     *
178
     * update field
179
     */
180
    public function setobjectfield()
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...
181
    {
182
        if (isset($_REQUEST["F"]) && $_REQUEST["F"]== "TESTONLY") {
183
            return "THIS IS FOR TESTING ONLY";
184
        }
185
        // 1) Check that all parameters have been specified
186
187 View Code Duplication
        foreach (array('T', 'I', 'F', 'V') as $field) {
0 ignored issues
show
Duplication introduced by
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...
188
            if (! isset($_REQUEST[$field])) {
189
                return "$field value missing";
190
            }
191
        }
192
193
        // 2 Check the parameters values
194
195
        $result = 1; // Updated
196
197
        $objectClass = $_REQUEST['T'];
198
        if (! class_exists($objectClass)) {
199
            return 'ObjectClass value incorrect';
200
        }
201
202
        $objectID = $_REQUEST['I'];
203
        if ($objectClass == 'CountryPrice' && is_array($objectID)) {
204
            $object = new $objectClass($objectID);
205
            $objectID = $object->write();
206
            $result = $objectID; // Added
207
        } elseif (intval($objectID)) {
208
            $objectID = intval($objectID);
209
            $object = $objectClass::get()->byID($objectID);
210
            if (! $object) {
211
                return 'ObjectID (ID: $objectID, Class Name: $objectClass) value incorrect';
212
            }
213
        } else {
214
            return 'ObjectID value missing...';
215
        }
216
217
        //check if object can be edited!
218
        if (!$this->canEditThisObject($objectClass, $objectID)) {
219
            return 'You can not edit this object';
220
        }
221
        $fieldName = Convert::raw2sql($_REQUEST['F']);
222
        $value = $_REQUEST['V'];
223
224
        if ($fieldName == 'Price' && (! is_numeric($value) || $value < 0)) {
225
            return 'Price value incorrect';
226
        }
227
        if ($value == '0') {
228
            $object->delete();
229
            $result = 'deleted';
230
        } else {
231
            $object->$fieldName = $value;
232
            $object->write();
233
        }
234
235
236
        //create log
237
        $log = new CountryPrice_DistributorManagementTool_Log();
238
        $member = Member::currentUser();
239
        $log->UserEmail = $member->Email;
0 ignored issues
show
Documentation introduced by
The property UserEmail does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
240
        $log->ObjectClass = $objectClass;
0 ignored issues
show
Documentation introduced by
The property ObjectClass does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
241
        $log->ObjectID = $objectID;
0 ignored issues
show
Documentation introduced by
The property ObjectID does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
242
        $log->FieldName = $fieldName;
0 ignored issues
show
Documentation introduced by
The property FieldName does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
243
        $log->NewValue = $value;
0 ignored issues
show
Documentation introduced by
The property NewValue does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
244
        if ($this->distributor) {
245
            $log->DistributorID = $this->distributor->ID;
0 ignored issues
show
Documentation introduced by
The property DistributorID does not exist on object<CountryPrice_Dist...utorManagementTool_Log>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
246
        }
247
        $log->write();
248
        return $result;
249
    }
250
251
252
    /**
253
     * Title for page
254
     * @return String
255
     */
256
    public function DistributorTitle()
257
    {
258
        return Permission::check('ADMIN') ? 'Shop Administrator' : $this->distributor->Name;
0 ignored issues
show
Documentation introduced by
The property Name does not exist on object<Distributor>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
259
    }
260
261
    /**
262
     * @return string
263
     */
264
    public function DistributorFilterList()
265
    {
266
        $html = "";
267
        if (!$this->distributor) {
268
            $distributors = Distributor::get();
269
            foreach ($distributors as $distributor) {
270
                $countries = $distributor->Countries();
271
                if ($countries && $countries->count()) {
272
                    $html .= "
273
                        <li>
274
                            <a href=\"#Distributor".$distributor->ID."\" data-name=\"Distributor".$distributor->ID."\" data-countries=\"".implode(",", $countries->map("ID", "ID")->toArray())."\">".
275
                                $distributor->Name.
276
                            "</a>
277
                        </li>
278
                    ";
279
                }
280
            }
281
        }
282
        return $html;
283
    }
284
285
    /**
286
     * returns list of Distributor Fields
287
     * @return String
288
     */
289
    public function Distributors()
290
    {
291
        $html = "";
292
        $where = "";
293
        if ($this->distributor) {
294
            $where = "ID = {$this->distributor->ID}";
295
        }
296
        $distributors = Distributor::get()
297
            ->where($where);
298
        if ($distributors && $distributors->count()) {
299
            foreach ($distributors as $distributor) {
300
                $data = array('T' => 'Distributor', 'I' => $distributor->ID);
301
                $html .= $this->createTreeNode(
302
                    $distributor->Name,
303
                    "",
304
                    array($distributor)
305
                );
306
                $html .= $this->createEditNode(
307
                    "Name",
308
                    "",
309
                    $distributor->Name,
310
                    $data + array("F" => "Name")
311
                );
312
                $distributorFields = array(
313
                    'Email',
314
                    'Address1',
315
                    'Address2',
316
                    'Address3',
317
                    'Address4',
318
                    'Address5',
319
                    'Phone',
320
                    'DisplayEmail',
321
                    'WebAddress',
322
                    'DeliveryCostNote',
323
                    'ShippingEstimation',
324
                    'ReturnInformation'
325
                );
326
                foreach ($distributorFields as $distributorField) {
327
                    $html .= $this->createEditNode(
328
                    $distributorField,
329
                    "",
330
                    $distributor->$distributorField,
331
                    $data + array("F" => $distributorField)
332
                );
333
                }
334
                if (Permission::check("ADMIN")) {
335
                    $html .= $this->createEditNode(
336
                        "Default " . _t('Distributor.SINGULAR_NAME', 'Distributor'),
337
                        $distributor->IsDefault ? "YES" : "NO"
338
                    );
339
                }
340
341
                //countries
342
                $countryList = array();
343
                $countries = $distributor->Countries();
344
                foreach ($countries as $country) {
345
                    $countryList[] = $country->Name . ($country->DoNotAllowSales ? ' (Sales not allowed)' : '');
346
                }
347
                $html .= $this->createEditNode(
348
                    'Countries',
349
                    implode(', ', $countryList)
350
                );
351
352
                //users
353
                $memberList = "";
354
                if ($members = $distributor->Members()) {
355
                    if ($members->count()) {
356
                        $memberList = implode(", ", $members->map("ID", "Email")->toArray());
357
                    }
358
                }
359
                $html .= $this->createEditNode(
360
                    "Registered editors",
361
                    $memberList
362
                );
363
                $html .= $this->createEditNode(
364
                    "Passwords?",
365
                    '
366
                        ' . _t('Distributor.SINGULAR_NAME', 'Distributor').' can log in using the email(s) listed above.
367
                        If they do not have a password they can request a
368
                        <a href="/Security/lostpassword">password reset</a>.
369
                    '
370
                );
371
                $html .= $this->closeTreeNode();
372
            }
373
        }
374
        return $html;
375
    }
376
377
378
    /**
379
     * returns list of Country Fields
380
     * @return String
381
     */
382
    public function AllowSalesTo()
383
    {
384
        $html = "";
385
        $countries = EcommerceCountry::get()
386
            ->filter(
387
                array(
388
                    "DoNotAllowSales" => 0,
389
                    "Code" => $this->countryArray
390
                )
391
            )
392
            ->exclude(array("DistributorID" => 0));
393
        if ($countries && $countries->count()) {
394
            foreach ($countries as $country) {
395
396
                //delivery options
397
                $deliveryOptionItems = PickUpOrDeliveryModifierOptions::get_all_as_country_array();
398
                $deliveryOptions = "";
399
                if ($deliveryOptionItems) {
400
                    foreach ($deliveryOptionItems as $deliveryOptionCode => $countryCodes) {
401
                        foreach ($countryCodes as $countryCode) {
402
                            if ($countryCode == $country->Code) {
403
                                $deliveryOptions .= $deliveryOptionCode.", ";
404
                            }
405
                        }
406
                    }
407
                }
408
409
                //tax options
410
                $taxesObjects = GSTTaxModifierOptions::get()
411
                    ->filter(
412
                        array(
413
                            "CountryCode" => $country->Code
414
                        )
415
                    );
416
                if ($taxesObjects && $taxesObjects->count()) {
417
                    $taxes = implode(",", $taxesObjects->map("ID", "Name")->toArray());
418
                } else {
419
                    $taxes = "";
420
                }
421
422
                $countrySpecificMessages = "tba";
423
                //compile
424
                $data = array('T' => 'EcommerceCountry', 'I' => $country->ID);
425
                $distributorName = $country->Distributor()->Name;
426
                if (!$distributorName) {
427
                    $distributorName = "<p class=\"message bad\">No ". _t('Distributor.SINGULAR_NAME', 'Distributor') ." has been assigned to this country.</p>";
428
                }
429
                $html .= $this->createTreeNode($country->Code." - ".$country->Name, $country->Code, array($country));
430
                $distributorTitlePlural = _t('Distributor.PLURAL_NAME', 'Distributor');
0 ignored issues
show
Unused Code introduced by
$distributorTitlePlural 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...
431
                $distributorTitleSingluar = _t('Distributor.SINGULAR_NAME', 'Distributor');
432
                $html .= $this->createEditNode($distributorTitleSingluar, $distributorName);
433
                $html .= $this->createEditNode("FAQ Content", "", $country->FAQContent, $data + array("F" => "FAQContent"), "textarea");
434
                $html .= $this->createEditNode("Top Bar Message", "", $country->TopBarMessage, $data + array("F" => "TopBarMessage"), "");
435
                $html .= $this->createEditNode("Country Specific Messages", $countrySpecificMessages);
436
                $html .= $this->createEditNode("Delivery Options", $deliveryOptions);
437
                $html .= $this->createEditNode("Taxes", $taxes);
438
                $paymentOptions = EcommercePayment::get_supported_methods();
439
                $html .= $this->createEditNode("Payment Options", implode(',', array_keys($paymentOptions)));
440
441
                $html .= $this->closeTreeNode();
442
            }
443
        }
444
        $countries =  EcommerceCountry::get()->filter(array("DistributorID" => 0, "DoNotAllowSales" => 0));
445 View Code Duplication
        if ($countries && $countries->count()) {
0 ignored issues
show
Duplication introduced by
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...
446
            $list = implode(", ", $countries->map("ID", "Code")->toArray());
447
            $html .= $this->createEditNode("Countries without a ". _t('Distributor.SINGULAR_NAME', 'Distributor') ." that allow sales", $list);
448
        }
449
        $countries =  EcommerceCountry::get()->filter(array("DistributorID" => 0, "DoNotAllowSales" => 1));
450 View Code Duplication
        if ($countries && $countries->count()) {
0 ignored issues
show
Duplication introduced by
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...
451
            $list = implode(", ", $countries->map("ID", "Code")->toArray());
452
            $html .= $this->createEditNode("Countries without a ". _t('Distributor.SINGULAR_NAME', 'Distributor') ." that do not allow sales", $list);
453
        }
454
        return $html;
455
    }
456
457
458
    /**
459
     * returns list of Product Fields
460
     * @return String
461
     */
462
    public function Products()
463
    {
464
        $html = "";
465
        $where = "";
0 ignored issues
show
Unused Code introduced by
$where 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...
466
        $countryArray = array();
0 ignored issues
show
Unused Code introduced by
$countryArray 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...
467
        $products = Product::get()
468
            ->filter(array("AllowPurchase" => 1))
469
            ->sort("FullSiteTreeSort", "ASC");
470
        $defaultPriceText = ' (N.B. This is default for new variations ONLY - set actual prices under variations)';
471
        if ($products && $products->count()) {
472
            foreach ($products as $product) {
473
                $withDefaultPrices = Permission::check('ADMIN') || (! $product->hasVariations());
474
                $html .= $this->createTreeNode($product->FullName, "pricing", array($product));
475
476
                //country exceptions
477
                if (Permission::check('ADMIN')) {
478
                    $includedCountries = $product->IncludedCountries();
479
                    if ($includedCountries && $includedCountries->Count()) {
480
                        $html .= $this->createEditNode(
481
                            "Additional countries this product is sold ... ",
482
                            implode(", ", $includedCountries->map("ID", "Code")->toArray())
483
                        );
484
                    }
485
                    $excludedCountries = $product->ExcludedCountries();
486
                    if ($excludedCountries && $excludedCountries->Count()) {
487
                        $html .= $this->createEditNode(
488
                            "This product is not sold in ... ",
489
                            implode(", ", $excludedCountries->map("ID", "Code")->toArray())
490
                        );
491
                    }
492
                    //only show default price for ShopAdmin
493
                    if ($withDefaultPrices) {
494
                        $html .= $this->createEditNode(
495
                            'Default Price' . ($product->hasVariations() ? $defaultPriceText : ''),
496
                            EcommercePayment::site_currency(),
497
                            $product->Price,
498
                            array(
499
                                "T" => "Product",
500
                                "F" => "Price",
501
                                "I" => $product->ID
502
                            )
503
                        );
504
                    }
505
                }
506
507
                //country prices
508
                $outstandingCountries = $this->countryArray;
509
                if ($withDefaultPrices) {
510
                    $html .= $this->createTreeNode(
511
                        'Country Prices' . ($product->hasVariations() ? $defaultPriceText : ''),
512
                        " pricing countryPrices"
513
                    );
514
                }
515
                $arrayOfProductCountryCurencyPrices = array();
516
                $countriesWithProductPrices = array();
0 ignored issues
show
Unused Code introduced by
$countriesWithProductPrices 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...
517
                $countryPricesObjects = $product->AllCountryPricesForBuyable();
518
                if ($countryPricesObjects->count()) {
519
                    foreach ($countryPricesObjects as $countryPricesObject) {
520
                        $arrayOfProductCountryCurencyPrices[$countryPricesObject->Currency.$countryPricesObject->Country] = $countryPricesObject->Currency.$countryPricesObject->Country;
521
                        $countryObject = $countryPricesObject->CountryObject();
522
                        if (!$countryObject) {
523
                            break;
524
                        }
525
                        $countryID = array_search($countryPricesObject->Country, $outstandingCountries);
526
                        if (Permission::check('ADMIN') || $countryID !== false) {
527
                            $data = array(
528
                                "T" => "CountryPrice",
529
                                "I" => $countryPricesObject->ID,
530
                                "F" => "Price"
531
                            );
532
                            $countryName = EcommerceCountry::find_title($countryPricesObject->Country);
533
                            if ($withDefaultPrices) {
534
                                $html .= $this->createEditNode(
535
                                    $countryPricesObject->Country . ' - '. $countryName,
536
                                    $countryPricesObject->Currency,
537
                                    $countryPricesObject->Price,
538
                                    $data,
539
                                    "input",
540
                                    array($countryObject),
0 ignored issues
show
Documentation introduced by
array($countryObject) is of type array<integer,?,{"0":"?"}>, but the function expects a object<DataList>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
541
                                    '[x]'
542
                                );
543
                            }
544
                            unset($outstandingCountries[$countryID]);
545
                        }
546
                    }
547
                }
548
                $addText = 'Add price to start selling';
549 View Code Duplication
                foreach ($outstandingCountries as $countryCode) {
0 ignored issues
show
Duplication introduced by
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...
550
                    if ($countryCode != EcommerceConfig::get('EcommerceCountry', 'default_country_code')) {
551
                        $countryObject = EcommerceCountry::get()->filter(array("Code" => $countryCode))->first();
552
                        if (!$countryObject) {
553
                            user_error("country not found");
554
                        }
555
                        $currencyObject = $countryObject->EcommerceCurrency();
556
                        $data = array(
557
                            "T" => "CountryPrice",
558
                            "I" => array(
559
                                'Country' => $countryCode,
560
                                'Currency' => $currencyObject->Code,
561
                                'ObjectClass' => $product->ClassName,
562
                                'ObjectID' => $product->ID
563
                            ),
564
                            'F' => 'Price'
565
                        );
566
                        $countryName = EcommerceCountry::find_title($countryCode);
567
                        if ($withDefaultPrices) {
568
                            $html .= $this->createEditNode(
569
                                $countryCode . ' - '. $countryName,
570
                                $currencyObject->Code,
571
                                $addText,
572
                                $data,
573
                                "input",
574
                                array($countryObject),
0 ignored issues
show
Documentation introduced by
array($countryObject) is of type array<integer,null|objec...l|object<DataObject>"}>, but the function expects a object<DataList>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
575
                                '[x]',
576
                                'add-node'
577
                            );
578
                        }
579
                    }
580
                }
581
                if ($withDefaultPrices) {
582
                    $html .= $this->closeTreeNode();
583
                }
584
                if ($product->hasVariations()) {
585
                    $variations = $product->Variations();
586
                    if ($variations && $variations->count()) {
587
                        $html .= $this->createTreeNode("Variations", "variations pricing");
588
                        $variations = $product->Variations();
589
                        foreach ($variations as $variation) {
590
                            if ($variation->AllowPurchase) {
591
                                $html .= $this->createTreeNode($variation->getTitle());
592
                                if (Permission::check('ADMIN')) {
593
                                    $html .= $this->createEditNode(
594
                                        "Default Price",
595
                                        EcommercePayment::site_currency(),
596
                                        $variation->Price,
597
                                        array(
598
                                            "T" => "ProductVariation",
599
                                            "F" => "Price",
600
                                            "I" => $variation->ID
601
                                        )
602
                                    );
603
                                }
604
                                $outstandingCountries = $this->countryArray;
605
                                $countryPricesObjects = $variation->AllCountryPricesForBuyable();
606
                                $html .= $this->createTreeNode("Variation Country Prices", " pricing countryPrices variationCountryPrices");
607
                                if ($countryPricesObjects->count()) {
608
                                    $lowestPrice = 999999;
609
                                    foreach ($countryPricesObjects as $countryPricesObject) {
610
                                        $countryObject = $countryPricesObject->CountryObject();
611
                                        if (!$countryObject) {
612
                                            break;
613
                                        }
614
                                        $countryID = array_search($countryPricesObject->Country, $outstandingCountries);
615
                                        if (Permission::check('ADMIN') || $countryID !== false) {
616
                                            $data = array(
617
                                                "T" => "CountryPrice",
618
                                                "I" => $countryPricesObject->ID,
619
                                                "F" => "Price"
620
                                            );
621
                                            $countryName = EcommerceCountry::find_title($countryPricesObject->Country);
622
                                            $html .=  $this->createEditNode(
623
                                                $countryPricesObject->Country . ' - '. $countryName,
624
                                                $countryPricesObject->Currency,
625
                                                $countryPricesObject->Price,
626
                                                $data,
627
                                                "input",
628
                                                array($countryObject),
0 ignored issues
show
Documentation introduced by
array($countryObject) is of type array<integer,?,{"0":"?"}>, but the function expects a object<DataList>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
629
                                                '[x]'
630
                                            );
631
                                            if ($countryPricesObject->Price < $lowestPrice) {
632
                                                $lowestPrice = $countryPricesObject->Price;
633
                                            }
634
                                            unset($outstandingCountries[$countryID]);
635
                                        }
636
                                    }
637
                                    if ($lowestPrice > 0 && $lowestPrice < 999999) {
638
                                        if (!in_array($countryPricesObject->Currency.$countryPricesObject->Country, $arrayOfProductCountryCurencyPrices)) {
639
                                            $sql = '
640
                                                INSERT INTO "CountryPrice" ("Created","LastEdited","Price","Country","Currency","ObjectClass","ObjectID")
641
                                                VALUES (NOW(), NOW(), \''.$lowestPrice.'\',\''.$countryPricesObject->Country.'\',\''.$countryPricesObject->Currency.'\',\''.$product->ClassName.'\','.$product->ID.')
0 ignored issues
show
Bug introduced by
The variable $countryPricesObject does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
642
                                                ON DUPLICATE KEY
643
                                                    UPDATE "LastEdited" = VALUES("LastEdited"), "Price" = VALUES("Price")
644
                                            ';
645
                                            DB::alteration_message("adding product price for ".$product->Title." in ".$countryPricesObject->Country." because there are variation prices");
646
                                            DB::query($sql);
647
                                        }
648
                                    }
649
                                }
650 View Code Duplication
                                foreach ($outstandingCountries as $countryCode) {
0 ignored issues
show
Duplication introduced by
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...
651
                                    if ($countryCode != EcommerceConfig::get('EcommerceCountry', 'default_country_code')) {
652
                                        $countryObject = EcommerceCountry::get()->filter(array("Code" =>$countryCode))->first();
653
                                        if (!$countryObject) {
654
                                            user_error("country not found");
655
                                        }
656
                                        $currency = $countryObject->EcommerceCurrency();
657
                                        $data = array(
658
                                            "T" => "CountryPrice",
659
                                            "I" => array(
660
                                                'Country' => $countryCode,
661
                                                'Currency' => $currency->Code,
662
                                                'ObjectClass' => $variation->ClassName,
663
                                                'ObjectID' => $variation->ID
664
                                            ),
665
                                            'F' => 'Price'
666
                                        );
667
                                        $countryName = EcommerceCountry::find_title($countryCode);
668
                                        $html .= $this->createEditNode(
669
                                            $countryCode . ' - '. $countryName,
670
                                            $currency->Code,
671
                                            $addText,
672
                                            $data,
673
                                            "input",
674
                                            array($countryObject)
0 ignored issues
show
Documentation introduced by
array($countryObject) is of type array<integer,null|objec...l|object<DataObject>"}>, but the function expects a object<DataList>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
675
                                        );
676
                                    }
677
                                }
678
                                $html .= $this->closeTreeNode();
679
                                $html .= $this->closeTreeNode();
680
                            }
681
                        }
682
                        $html .= $this->closeTreeNode();
683
                    }
684
                }
685
                $html .= $this->closeTreeNode();
686
            }
687
        } else {
688
            $html .= $this->createEditNode("Products");
689
        }
690
        return $html;
691
    }
692
693
    /**
694
     * returns list of Currencies with info
695
     * @return String
696
     */
697
    public function Currencies()
698
    {
699
        $html = "";
700
        $currencies = EcommerceCurrency::get();
701
        foreach ($currencies as $currency) {
702
            $priceCount = CountryPrice::get()->filter(array("Currency" => $currency->Code))->count();
703
            if ($priceCount) {
704
                $name = $currency->Code." ($priceCount price points)";
705
                if ($currency->IsDefault()) {
706
                    $name .= " [DEFAULT CURRENCY]";
707
                }
708
                $html .= $this->createTreeNode($name, "currencies");
709
                $html .= $this->createEditNode(
710
                    'Countries',
711
                    "tba"
712
                );
713
                $html .= $this->closeTreeNode();
714
            }
715
        }
716
        //$html .= $this->createTreeNode("Currencies");
717
        return $html;
718
    }
719
720
721
    /********************
722
     * internal methods
723
     ********************/
724
725
726
    /**
727
     * returns the opening of a list (<li>Title<ul>)
728
     * @param String $title - e.g. My items
729
     * @param String $classOrCountryCode -e.g. myCSSClass or NZ
730
     * @param Array list of objects used...
731
     * @return String
732
     */
733
    private function createTreeNode($title, $classOrCountryCode = "", $objectArray = array())
734
    {
735
        $class = "";
736
        if (strlen($classOrCountryCode) == 2 && $img = $this->codeToFlag($classOrCountryCode)) {
737
            $title = $img.$title;
738
            $classOrCountryCode = "";
0 ignored issues
show
Unused Code introduced by
$classOrCountryCode 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...
739
        } elseif ($classOrCountryCode) {
740
            $class = " class=\"$classOrCountryCode\"";
741
        }
742
        $filterClass = '';
743 View Code Duplication
        foreach ($objectArray as $object) {
0 ignored issues
show
Duplication introduced by
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...
744
            $filterClass .= ' '.$object->ClassName.$object->ID.' gp'.$object->ClassName;
745
        }
746
        return "<li class=\"$filterClass\"><strong>$title</strong><ul{$class}>";
747
    }
748
749
750
    /**
751
     * returns the opening of a list (<li>Title<ul>)
752
     * @return String
753
     */
754
    private function closeTreeNode()
755
    {
756
        return "</ul></li>";
757
    }
758
759
    /**
760
     * returns the opening of a list (<li>Title<ul>)
761
     * @param String $label - e.g. My Price
762
     * @param String $nonEditText - e.g. USD
763
     * @param String $editText - e.g. 99.95
764
     * @param Array $data - should include the following: "T", "I", "F"
0 ignored issues
show
Documentation introduced by
Should the type for parameter $data not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
765
     * @param String $fieldType -e.g. input, textarea, checkbox
766
     * @param DataList $objectArray -e.g. input, textarea, checkbox
0 ignored issues
show
Documentation introduced by
Should the type for parameter $objectArray not be DataList|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
767
     * @return String (<li>edit me</li>)
768
     */
769
    private function createEditNode(
770
        $label,
771
        $nonEditText = "",
772
        $editText = "",
773
        $data = null,
774
        $fieldType = "input",
775
        $objectArray = null,
776
        $deleteText = '',
777
        $extraClassesString = ''
778
779
    ) {
780
        if (!$data) {
781
            $ddClass = "readonly";
782
            $editTextNode = "";
783
        } else {
784
            $ddClass = "editable";
785
            $editTextNode = "<a href=\"#\" class=\"edit\">$editText</a>";
786
        }
787
        if (strlen($label) == 2 && $img = $this->codeToFlag($label)) {
788
            $label = $img.$label;
789
        }
790
        //can be edited but there is no data
791
        if (($data && !$editText)) {
792
            $editText = "[NONE]";
0 ignored issues
show
Unused Code introduced by
$editText 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...
793
            ;
794
        }
795
        //can not be edited and there is no data
796
        elseif (!$data && !$editText && !$nonEditText) {
797
            $nonEditText = "[NONE]";
798
        }
799
        $fieldTypeString = "";
800
        if ($fieldType && $fieldType != "input") {
801
            $fieldTypeString = " data-$fieldType=\"1\"";
802
        }
803
        $nonEditTextNode = "";
804
        if ($nonEditText) {
805
            $nonEditTextNode = "<div class=\"nonEditablePart\">$nonEditText</div>";
806
        }
807
        if ($editTextNode) {
808
            $editTextNode = "<div class=\"editablePart\">$editTextNode</div>";
809
        }
810
        if ($data) {
811 View Code Duplication
            foreach (array("T", "F", "I") as $key) {
0 ignored issues
show
Duplication introduced by
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...
812
                if (!isset($data[$key])) {
813
                    user_error("data must contain T (table), F (field) and I (ID) value");
814
                }
815
            }
816
            $data = " data-name=\"".Convert::raw2att(Convert::raw2json($data))."\"";
817
        }
818
        $filterClass = $extraClassesString;
819
        if ($objectArray) {
820 View Code Duplication
            foreach ($objectArray as $object) {
0 ignored issues
show
Duplication introduced by
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...
821
                $filterClass .= ' '.$object->ClassName.$object->ID.' gp'.$object->ClassName;
822
            }
823
        }
824
        $deleteLink = '';
825
        if ($deleteText) {
826
            $deleteLink = '<a href="#" class="delete-record">'.$deleteText.'</a>';
827
        }
828
        return "
829
                    <li{$data}{$fieldTypeString} class=\"$filterClass \">
830
                        <dl>
831
                            <dt>$label</dt>
832
                            <dd class=\"$ddClass valueHolder\">
833
                                $nonEditTextNode
834
                                $editTextNode
835
                                $deleteLink
836
                            </dd>
837
                        </dl>
838
                    </li>";
839
    }
840
841
    private static $flag_cache = array();
842
843
    /**
844
     * turn code into image flag
845
     * @param String $code
846
     * @return String html for flag
847
     */
848
    private function codeToFlag($code)
849
    {
850
        if (isset(self::$flag_cache[$code])) {
851
            return self::$flag_cache[$code];
852
        }
853
        $wwwLocation = "/themes/main/images/flags/".strtolower($code).".png";
854
        $fileLocation = Director::baseFolder().$wwwLocation;
855
        if (file_exists($fileLocation)) {
856
            self::$flag_cache[$code] = "<img src=\"$wwwLocation\" alt=\"$code\" /> ";
857
        } else {
858
            self::$flag_cache[$code] = false;
859
        }
860
        return self::$flag_cache[$code];
861
    }
862
863
864
    /**
865
     * turn code into image flag
866
     * @param String $table
867
     * @param Int $id
868
     * @return Boolean
869
     */
870
    private function canEditThisObject($table, $id)
871
    {
872
        if (Permission::check('ADMIN')) {
873
            return true;
874
        }
875
        switch ($table) {
876
            case 'Distributor':
877
                if ($this->distributor->ID == $id) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return $this->distributor->ID == $id;.
Loading history...
878
                    return true;
879
                }
880
                return false;
881
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
882
            case 'EcommerceCountry':
883
                $obj = EcommerceCountry::get()->byID($id);
884
                return in_array($obj->Code, $this->countryArray);
885
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
886
            case 'CountryPrice':
887
                $obj = CountryPrice::get()->byID($id);
888
                return in_array($obj->Country, $this->countryArray);
889
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
890
            case 'Currency':
891
                return false;
892
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
893
            default:
894
                return false;
895
        }
896
        return false;
897
    }
898
}
899