GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( bee3fd...584b84 )
by
unknown
01:56
created

SecondHandProduct::onBeforeWrite()   D

Complexity

Conditions 10
Paths 36

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 17
nc 36
nop 0

How to fix   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
class SecondHandProduct extends Product implements PermissionProvider
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...
5
{
6
    private static $can_be_root = false;
0 ignored issues
show
Unused Code introduced by
The property $can_be_root 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...
7
8
    /**
9
     * halt purchase for ... number of days
10
     * from the day of creation.
11
     * @var int
12
     */
13
    private static $embargo_number_of_days = 0;
0 ignored issues
show
Unused Code introduced by
The property $embargo_number_of_days 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...
14
15
    /**
16
     * Restrict GoogleAddressField to a specific Country
17
     * E.g. for New Zealand, $country_code =  'NZ'
18
     * @var string
19
     */
20
    private static $country_code = null;
0 ignored issues
show
Unused Code introduced by
The property $country_code 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...
21
    /**
22
     * stadard SS declaration
23
     * @var Array
24
     */
25
    private static $db = 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...
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...
26
        'PurchasePrice' => 'Currency',
27
        'ProductQuality' => 'ENUM("1, 2, 3, 4, 5, 6, 7, 8, 9, 10","10")',
28
        'IncludesBoxOrCase' => "ENUM('No, Box, Case, Both','No')",
29
        'SellingOnBehalf' => 'Boolean',
30
        'OriginalManual' => 'Boolean',
31
        'DateItemWasBought' => 'Date',
32
        'DateItemWasSold' => 'Date',
33
        'SerialNumber' => 'VarChar(50)',
34
        'SellersName' =>  'VarChar(50)',
35
        'SellersPhone' =>  'VarChar(30)',
36
        'SellersEmail' =>  'VarChar(255)',
37
        'SellersAddress' =>  'VarChar(255)',
38
        'SellersAddress2' => 'Varchar(255)',
39
        'SellersCity' => 'Varchar(100)',
40
        'SellersPostalCode' => 'Varchar(50)',
41
        'SellersRegionCode' => 'Varchar(100)',
42
        'SellersCountry' => 'Varchar(50)',
43
        'SellersIDType' => 'ENUM(",Drivers Licence, Firearms Licence, Passport","")',
44
        'SellersIDNumber' => 'Varchar(50)',
45
        'SellersDateOfBirth' => 'Date',
46
        'SellersIDExpiryDate' => 'Date',
47
        'SellersIDPhotocopy' => 'Boolean'
48
    );
49
50
    private static $has_one = 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...
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...
51
        'BasedOn' => 'SecondHandProduct'
52
    );
53
54
    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...
55
        'Created' => 'DESC'
56
    );
57
58
    private static $defaults = 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...
Unused Code introduced by
The property $defaults 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...
59
        'ShowInMenus' => false
60
    );
61
62
    private static $indexes = 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...
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...
63
        'SerialNumber' => true
64
    );
65
66
    private static $casting = 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...
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...
67
        'SellersSummary' => 'Varchar',
68
        'CreatedNice' => 'Varchar'
69
    );
70
71
    private static $seller_summary_detail_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $seller_summary_detail_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...
72
        'SellersName',
73
        'SellersPhone',
74
        'SellersEmail',
75
        'SellersAddress',
76
        'SellersAddress2',
77
        'SellersCity',
78
        'SellersPostalCode',
79
        'SellersRegionCode',
80
        'SellersCountry',
81
        'SellersIDType',
82
        'SellersIDNumber',
83
        'SellersDateOfBirth',
84
        'SellersIDExpiryDate',
85
        'SellersIDPhotocopy'
86
    );
87
88
    private static $searchable_fields = 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...
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...
89
        'FullName' => array(
90
            'title' => 'Keyword',
91
            'field' => 'TextField',
92
        ),
93
        'Price' => array(
94
            'title' => 'Price',
95
            'field' => 'NumericField',
96
        ),
97
        'InternalItemID' => array(
98
            'title' => 'Internal Item ID',
99
            'filter' => 'PartialMatchFilter',
100
        ),
101
        'SellersName' => array(
102
            'title' => 'Sellers Name',
103
            'filter' => 'PartialMatchFilter',
104
        ),
105
        'SellersPhone' => array(
106
            'title' => 'Sellers Phone',
107
            'filter' => 'PartialMatchFilter',
108
        ),
109
        'SellersEmail' => array(
110
            'title' => 'Sellers Email',
111
            'filter' => 'PartialMatchFilter',
112
        ),
113
        'AllowPurchase',
114
        'PurchasePrice' => 'ExactMatchFilter',
115
        'SerialNumber' => 'PartialMatchFilter'
116
    );
117
118
    public function getSellerSummary()
119
    {
120
        $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
121
        $array = array();
122
        foreach ($list as $field) {
0 ignored issues
show
Bug introduced by
The expression $list of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
123
            if (trim($this->$field)) {
124
                $array[] = $this->$field;
125
            }
126
        }
127
        return implode('; ', $array);
128
    }
129
130
    private static $second_hand_admin_group_code = 'second-hand-managers';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_group_code 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...
131
132
    private static $second_hand_admin_group_name = 'Second Hand Product Managers';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_group_name 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...
133
134
    private static $second_hand_admin_role_title = 'Second Hand Product Management';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_role_title 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...
135
136
    private static $second_hand_admin_permission_code = 'CMS_ACCESS_SECOND_HAND_PRODUCTS';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_permission_code 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...
137
138
    private static $second_hand_admin_permission_title = 'Second Hand Product Manager';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_permission_title 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...
139
140
    private static $second_hand_admin_permission_help = 'Manages the second product products';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_permission_help 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...
141
142
    private static $second_hand_admin_user_email = '';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_user_email 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...
143
144
    private static $second_hand_admin_user_firstname = '';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_user_firstname 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...
145
146
    private static $second_hand_admin_user_surname = '';
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_user_surname 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...
147
148
    private static $second_hand_admin_user_password = "";
0 ignored issues
show
Unused Code introduced by
The property $second_hand_admin_user_password 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...
149
150
    /**
151
     * standard SS declaration
152
     * @var String
153
     */
154
    private static $icon = "ecommerce_second_hand_product/images/treeicons/SecondHandProduct";
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...
Unused Code introduced by
The property $icon 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...
155
156
    /**
157
     * Standard SS variable.
158
     */
159
    private static $singular_name = 'SecondHand Product';
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...
160
    public function i18n_singular_name()
161
    {
162
        return self::$singular_name;
163
    }
164
165
    /**
166
     * Standard SS variable.
167
     */
168
    private static $plural_name = 'SecondHand Products';
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...
169
    public function i18n_plural_name()
170
    {
171
        return self::$plural_name;
172
    }
173
174
    /**
175
     * standard SS declaration
176
     * @var String
177
     */
178
    private static $description = "This page displays a single secondhand product that can only be sold once";
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...
Unused Code introduced by
The property $description 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...
179
180
    /**
181
     * standard SS method
182
     * @return Boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|string|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...
183
     */
184
    public function canCreate($member = null)
185
    {
186
        return Permission::check(
187
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
188
            'any',
189
            $member
190
        );
191
    }
192
193
    /**
194
     * standard SS method
195
     * @return Boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|string|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...
196
     */
197
    public function canPublish($member = null)
198
    {
199
        return Permission::check(
200
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
201
            'any',
202
            $member
203
        );
204
    }
205
206
    /**
207
     * standard SS method
208
     * @return Boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|string|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...
209
     */
210
    public function canEdit($member = null)
211
    {
212
        return Permission::check(
213
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
214
            'any',
215
            $member
216
        );
217
    }
218
219
    /**
220
     * standard SS method
221
     * @return Boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|string|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...
222
     */
223
    public function canDelete($member = null)
224
    {
225
        return Permission::check(
226
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
227
            'any',
228
            $member
229
        );
230
    }
231
232
    public function onBeforeDelete()
233
    {
234
        SecondHandArchive::create_from_page($this);
235
        parent::onBeforeDelete();
236
    }
237
238
239
    /**
240
     * stadard SS method
241
     * @return FieldList
242
     */
243
    public function getCMSFields()
244
    {
245
        $fields = parent::getCMSFields();
246
        //remove all unneccessary fields and tabs
247
        $fields->removeByName("AlsoShowHere");
248
        $fields->removeByName("Tax");
249
        $fields->removeByName("Links");
250
        $fields->removeByName("Details");
251
        $fields->removeByName("Images");
252
        $fields->removeFieldFromTab('Root', 'Title');
253
        $fields->removeFieldFromTab('Root', 'URLSegment');
254
        $fields->removeFieldFromTab('Root', 'MenuTitle');
255
        $fields->removeFieldFromTab('Root', 'ShortDescription');
256
        $fields->removeFieldFromTab('Root', 'Content');
257
        $fields->removeFieldFromTab('Root', 'Metadata');
258
        $fields->removeFieldFromTab('Root', 'AddToCartLink');
259
260
        $fields->addFieldsToTab(
261
            'Root.Main',
262
            array(
263
                $allowPurchaseField = CheckboxField::create("AllowPurchase", "<strong>Allow product to be purchased</strong>"),
264
                $sellinOnBehalf = CheckboxField::create("SellingOnBehalf", "<strong>Selling on behalf</strong>"),
265
                $featuredProductField = CheckboxField::create('FeaturedProduct', _t('Product.FEATURED', '<strong>Featured Product</strong>')),
266
                TextField::create('Title', 'Product Title'),
267
            )
268
        );
269
        $secondhandProductCategories = SecondHandProductGroup::get();
270
        if ($secondhandProductCategories->count()) {
271
            $fields->addFieldToTab(
272
                'Root.Main',
273
                $categoryField = DropdownField::create(
274
                    'ParentID',
275
                    'Product Category',
276
                    $secondhandProductCategories->map()
277
                )
278
            );
279
        }
280
        $fields->addFieldsToTab(
281
            'Root.Main',
282
            array(
283
                ReadonlyField::create('CanBeSold', "For Sale", DBField::create_field('Boolean', $this->canPurchase())->Nice()),
284
                ReadonlyField::create('CreatedNice', "First Entered", $this->getCreatedNice()),
285
                TextField::create('InternalItemID', "Product Code"),
286
                $salePriceField = NumericField::create('Price', 'Sale Price'),
287
                $purchasePriceField = NumericField::create('PurchasePrice', 'Purchase Price'),
288
                $serialNumberField = TextField::create('SerialNumber', 'Serial Number'),
289
                $productQualityField = DropdownField::create(
290
                    "ProductQuality",
291
                    "Product Condition/Quality",
292
                    $this->dbObject('ProductQuality')->enumValues()
293
                ),
294
                $boxOrCaseField = DropdownField::create(
295
                    "IncludesBoxOrCase",
296
                    "Includes Box/Case",
297
                    $this->dbObject('IncludesBoxOrCase')->enumValues()
298
                ),
299
                $originalManualField = CheckboxField::create("OriginalManual", "Includes Original Manual"),
300
                $contentField = TextField::create("ShortDescription", "Description"),
301
                $boughtDate = DateField::create('DateItemWasBought', 'Date this item was bought'),
302
                $soldDate = DateField::create('DateItemWasSold', 'Date this item was sold'),
303
                $mainImageField = UploadField::create("Image", "Main Product Image"),
304
                $additionalImagesField = UploadField::create("AdditionalImages", "More Images"),
305
                $metaFieldDesc = TextareaField::create("MetaDescription", 'Meta Description')
306
            )
307
        );
308
        $soldDate->setDisabled(true);
309
310
        //set right titles and descriptions
311
        $featuredProductField->setDescription('If this box is ticked then this product will appear in the "Featured Products" box on the home page');
312
        $allowPurchaseField->setDescription("This box must be ticked to allow a customer to purchase it");
313
        $sellinOnBehalf->setDescription('This box must be ticked if this product is being sold on behalf');
314
        $salePriceField->setRightTitle("Selling price");
315
        $purchasePriceField->setRightTitle("Price paid for the product");
316
        $serialNumberField->setRightTitle("Enter the serial number of the product here");
317
        $originalManualField->setDescription("Tick this box if the product includes the original manual, otherwise leave it empty");
318
        $boxOrCaseField->setRightTitle("Does this product come with a box, case or both?");
319
        $contentField->setRightTitle("Optional text only description, the maximum length of this description is 255 characters.");
320
        $contentField->setMaxLength(255);
321
        $qualityFieldDescription = "A <strong>Condition Rating Page</strong> has yet to be setup";
322
        $obj = $this->EcomConfig()->SecondHandExplanationPage();
323
        if ($obj->exists()) {
324
            $qualityFieldDescription = 'An explanation of the ratings scale can be found by clicking this <a href="' . $obj->Link() . '">link</a>';
325
        }
326
        $productQualityField->setRightTitle($qualityFieldDescription);
327
        $boughtDate->setRightTitle('Date Format (dd-mm-YYYY). Example: 3rd of May 1992 should be entered as 03-05-1992');
328
        $mainImageField->setRightTitle(
329
            "<strong>Upload the main image for the product here.</strong><br>
330
            Recommended size: 810px wide x 418px high - but you can choose any width up to 810px, height must
331
            ALWAYS BE 418px. Should be provided to FTP data upload as productcode.jpg - e.g. 1003040.jpg.
332
            Images should be compressed up to 50%."
333
        );
334
        $additionalImagesField->setRightTitle(
335
            "<strong>Upload additional images here, you can upload as many as you want.</strong><br>
336
            Recommended size: 810px wide x 418px high - but you can choose any width up to 810px, height must
337
            ALWAYS BE 418px. Should be provided to FTP data upload as productcode.jpg - e.g. 1003040.jpg.
338
            Images should be compressed up to 50%."
339
        );
340
        //replace InternalItemID field with a read only field
341
        $fields->replaceField(
342
            'InternalItemID',
343
            $fields->dataFieldByName('InternalItemID')->performReadonlyTransformation()
344
        );
345
346
        $lastEditedItems = SecondHandProduct::get()->sort('Created', 'DESC')->limit(100);
347
348
        $lastItems = array(
349
            0 => '--- not based on previous sale ---'
350
        );
351
352
        foreach ($lastEditedItems as $lastEditedItem) {
353
            $details = $lastEditedItem->getSellerSummary();
354
            if ($details) {
355
                $lastItems[$lastEditedItem->ID] = $details;
356
            }
357
        }
358
359
        $fields->addFieldsToTab(
360
            'Root.SellersDetails',
361
            array(
362
                HeaderField::create('SellersDetails', 'Enter the details of the person who the product was purchased from'),
363
                DropdownField::create(
364
                    'BasedOnID',
365
                    'Autocomplete from saved items',
366
                    $lastItems),
367
                TextField::create('SellersName', 'Name'),
368
                TextField::create('SellersPhone', 'Phone'),
369
                TextField::create('SellersEmail', 'Email Address'),
370
                DropdownField::create(
371
                    'SellersIDType',
372
                    'ID Type',
373
                    $this->dbObject('SellersIDType')->enumValues()),
374
                TextField::create('SellersIDNumber', 'ID Number'),
375
                DateField::create('SellersDateOfBirth', 'Date of Birth'),
376
                DateField::create('SellersIDExpiryDate', 'ID Expiry Date'),
377
                CheckboxField::create('SellersIDPhotocopy', 'ID Photocopy')
378
            )
379
        );
380
381
        if (class_exists('GoogleAddressField')) {
382
            $mappingArray = $this->Config()->get('fields_to_google_geocode_conversion');
383
            if (is_array($mappingArray) && count($mappingArray)) {
384
                $fields->addFieldToTab(
385
                    'Root.SellersDetails',
386
                    $geocodingField = new GoogleAddressField(
387
                        'SellersAddressGeocodingField',
388
                        _t('OrderAddress.FIND_ADDRESS', 'Find address'),
389
                        Session::get('SellersAddressGeocodingFieldValue')
390
                    )
391
                );
392
                $geocodingField->setFieldMap($mappingArray);
393
394
                $country_code = Config::inst()->get('SecondHandProduct', 'country_code');
395
                if ($country_code) {
396
                    $geocodingField->setRestrictToCountryCode($country_code);
397
                }
398
                //$geocodingField->setAlwaysShowFields(true);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
399
            }
400
        }
401
402
        $fields->addFieldsToTab(
403
            'Root.SellersDetails',
404
            array(
405
                TextField::create('SellersAddress', 'Address'),
406
                TextField::create('SellersAddress2', 'Suburb'),
407
                TextField::create('SellersCity', 'City/Town'),
408
                TextField::create('SellersPostalCode', 'Postal Code'),
409
                TextField::create('SellersRegionCode', 'Region Code'),
410
                TextField::create('SellersCountry', 'Country'),
411
            )
412
        );
413
        //add all fields to the main tab
414
        $fields->addFieldToTab(
415
            'Root.SellersDetails',
416
            EcommerceCMSButtonField::create(
417
                'PrintView',
418
                $this->getPrintLink(),
419
                'Print Details',
420
                $newWindow = true
421
            )
422
        );
423
        if ($this->BasedOnID) {
424
            $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
425
            $labels = $this->FieldLabels();
0 ignored issues
show
Unused Code introduced by
$labels 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...
426
            foreach ($list as $listField) {
0 ignored issues
show
Bug introduced by
The expression $list of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
427
                $fields->replaceField(
428
                    $listField,
429
                    ReadonlyField::create(
430
                        $listField,
431
                        $fields->dataFieldByName($listField)->Title()
432
                    )
433
                );
434
            }
435
            $fields->removeByName('SellersAddressGeocodingField');
436
        }
437
        $fields->addFieldToTab(
438
            'Root.Categorisation',
439
            $categoriesTable = $this->getProductGroupsTableField()
440
        );
441
442
        // If the product has been sold all fields should be disabled
443
        // Only the shop administrator is allowed to undo this.
444
        if ($this->HasBeenSold()) {
445
            $fields = $fields->makeReadonly();
446
            $fields->replaceField($categoriesTable->Name, $categoriesTable);
447
            $categoriesTable->setConfig(GridFieldConfig_RecordViewer::create());
448
            $fields->replaceField(
449
                'EnquiresList',
450
                GridField::create(
451
                    'EnquiresList',
452
                    'Enquiries List',
453
                    $this->PageEnquiries(),
454
                    GridFieldConfig_RecordViewer::create()
455
                )
456
            );
457
        }
458
459
        if ($this->HasBeenSold() && Permission::check('ADMIN')) {
460
            $fields->replaceField('AllowPurchase', CheckboxField::create('AllowPurchase', '<strong>Allow product to be purchased</strong>'));
461
            $fields->replaceField('DateItemWasSold', DateField::create('DateItemWasSold', 'Date this item was sold'));
462
        }
463
464
        return $fields;
465
    }
466
467
    public function getPrintLink()
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...
468
    {
469
        return $this->link('printview');
470
    }
471
472
    public function CMSEditLink()
473
    {
474
        return Controller::join_links(
475
            singleton('SecondHandProductAdmin')->Link(),
476
            $this->ClassName,
477
            'EditForm',
478
            'field',
479
            $this->ClassName,
480
            'item',
481
            $this->ID,
482
            'edit'
483
        );
484
    }
485
486
    public function getSettingsFields()
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...
487
    {
488
        $fields = parent::getSettingsFields();
489
        $fields->removeByName('ParentID');
490
        return $fields;
491
    }
492
493
    public function canPurchase(Member $member = null, $checkPrice = true)
494
    {
495
        if ($this->HasBeenSold()) {
496
            return false;
497
        }
498
        $embargoDays = Config::inst()->get('SecondHandProduct', 'embargo_number_of_days');
499
        if (intval($embargoDays) > 0) {
500
            if ($this->DateItemWasBought) {
501
                $date = $this->DateItemWasBought;
502
            } else {
503
                $date = $this->Created;
504
            }
505
            $createdDate = strtotime($date);
506
            $daysOld = (time() - $createdDate) / (60 * 60 * 24);
507
            if ($daysOld <= $embargoDays) {
508
                return false;
509
            }
510
        }
511
        return parent::canPurchase($member, $checkPrice);
512
    }
513
514
    public function HasBeenSold()
515
    {
516
        if (parent::HasBeenSold()) {
517
            return true;
518
        }
519
        if ($this->DateItemWasSold) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return (bool) $this->DateItemWasSold;.
Loading history...
520
            return true;
521
        }
522
        return false;
523
    }
524
525
    public function onBeforeWrite()
526
    {
527
        if ($this->BasedOnID) {
528
            $basedOn = $this->BasedOn();
529
            if ($basedOn && $basedOn->exists()) {
530
                $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
531
                foreach ($list as $field) {
0 ignored issues
show
Bug introduced by
The expression $list of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
532
                    $this->$field = $basedOn->$field;
533
                }
534
            }
535
        }
536
        $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
0 ignored issues
show
Unused Code introduced by
$list 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...
537
538
        //set the IternatlItemID if it doesn't already exist
539
        if (! $this->InternalItemID) {
540
            //todo - this may need improvement
541
            $this->InternalItemID = "S-H-".strtoupper(substr(md5(microtime()), rand(0, 26), 5));
542
        }
543
        $this->URLSegment = $this->generateURLSegment($this->Title."-".$this->InternalItemID);
544
545
        if ($this->Title && strlen($this->MetaDescription) < 30) {
546
            $this->MetaDescription = "Second Hand Product: " . $this->Title;
547
        }
548
549
        // Save the date when the product was sold.
550
        if ($this->HasBeenSold()) {
551
            if (! $this->DateItemWasSold) {
552
                $this->DateItemWasSold = SS_Datetime::now()->Rfc2822();
553
            }
554
        }
555
        parent::onBeforeWrite();
556
    }
557
558
    public function SecondHandProductQualityPercentage()
559
    {
560
        return $this->ProductQuality * 10;
561
    }
562
563
    public function InternalItemIDNice()
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...
564
    {
565
        return $this->InternalItemID;
566
    }
567
568
    public function providePermissions()
569
    {
570
        $perms[EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code')] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$perms was never initialized. Although not strictly required by PHP, it is generally a good practice to add $perms = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
571
            'name' => EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_title'),
572
            'category' => 'E-commerce',
573
            'help' => EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_help'),
574
            'sort' => 250,
575
        );
576
        return $perms;
577
    }
578
579
    public function requireDefaultRecords()
580
    {
581
        parent::requireDefaultRecords();
582
        $permissionProviderFactory = Injector::inst()->get('PermissionProviderFactory');
583
        $member = $permissionProviderFactory->CreateDefaultMember(
584
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_email'),
585
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_firstname'),
586
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_surname'),
587
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_password')
588
        );
589
        $permissionProviderFactory->CreateGroup(
590
            $code = EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_group_code'),
591
            $name = EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_group_name'),
592
            $parentGroup = null,
593
            $permissionCode = EcommerceConfig::get(
594
                'SecondHandProduct',
595
                'second_hand_admin_permission_code'
596
            ),
597
            $roleTitle = EcommerceConfig::get(
598
                'SecondHandProduct',
599
                'second_hand_admin_permission_title'
600
            ),
601
            $permissionArray = array(
602
                'SITETREE_VIEW_ALL',
603
                'CMS_ACCESS_SecondHandProductAdmin',
604
            ),
605
            $member
606
        );
607
    }
608
609
    public function onAferSubmit($order)
610
    {
611
        DB::query('Update \"Product\" SET AllowPurchase = 0 WHERE \"Product\".\"ID\" = '.$this->ID);
612
        DB::query('Update \"Product_Live\" SET AllowPurchase = 0 WHERE \"Product_Live\".\"ID\" = '.$this->ID);
613
        $this->writeToStage('Stage');
614
        $this->doPublish();
615
    }
616
617
618
    /**
619
     * adds created as a summary field as we are sorting by created
620
     * @return array
621
     */
622
    public function summaryFields()
623
    {
624
        $fields = parent::summaryFields();
625
        $fields['CreatedNice'] = 'Entered';
626
        return $fields;
627
    }
628
629
630
    public function populateDefaults()
631
    {
632
        parent::populateDefaults();
633
        if (! $this->DateItemWasBought) {
634
            $this->DateItemWasBought = SS_Datetime::now()->Rfc2822();
635
        }
636
    }
637
638
639
    public function getCreatedNice()
640
    {
641
        if ($this->DateItemWasBought) {
642
            $date = $this->DateItemWasBought;
643
        } else {
644
            $date = $this->Created;
645
        }
646
        return $date.' = '.DBField::create_field('Date', $date)->Ago();
647
    }
648
}
649
650
class SecondHandProduct_Controller extends Product_Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
651
{
652
    private static $fields_to_remove_from_print = array(
653
        'CUS',
654
        'SPC',
655
        'MGP',
656
        'ZOR',
657
        'FPS',
658
        'SPE',
659
        'IOS',
660
        'PRO',
661
        'FER',
662
        'POA',
663
        'PHT',
664
        'NotForSaleMessage',
665
        'KeepRecordEvenThoughItIsNotForSale'
666
    );
667
668
    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...
Unused Code introduced by
The property $allowed_actions 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...
669
        'printview' => true
670
    );
671
672
    public function printview()
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...
673
    {
674
        if (!Permission::check('CMS_ACCESS_SECOND_HAND_PRODUCTS')) {
675
            return Security::permissionFailure($this, 'You do not have access to this feature, please login first.');
676
        }
677
        return $this->renderWith('SecondHandProduct_printview');
678
    }
679
680
    public function ListOfFieldsForPrinting()
681
    {
682
        $al = ArrayList::create();
683
        $fieldsWeNeed = $this->dataRecord->stat('db');
684
        $labels = $this->FieldLabels();
685
        foreach ($fieldsWeNeed as $fieldKey => $useless) {
686
            if (in_array($fieldKey, self::$fields_to_remove_from_print)) {
687
                unset($fieldsWeNeed[$fieldKey]);
688
            } else {
689
                $fieldsWeNeed[$fieldKey] = $labels[$fieldKey];
690
            }
691
        }
692
        $fields = $this->dataRecord->db();
693
        foreach ($fieldsWeNeed as $key => $description) {
694
            if (isset($fields[$key])) {
695
                $type = preg_replace('/\(.*\)/', '', $fields[$key]);
696
                $dbField = DBField::create_field($type, $this->$key);
697
                if ($dbField->hasMethod('Nice')) {
698
                    $value = $dbField->Nice();
699
                } else {
700
                    $value = $dbField->Raw();
701
                }
702
            } else {
703
                $value = "";
704
            }
705
            $al->push(
706
                ArrayData::create(
707
                    array(
708
                        'Key' => $description,
709
                        'Value' => $value
710
                    )
711
                )
712
            );
713
        }
714
        return $al;
715
    }
716
}
717