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.

SecondHandProduct::getSettingsFields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
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
        'SoldPrice' => 'Currency',
27
        'PurchasePrice' => 'Currency',
28
        'ProductQuality' => 'ENUM("1, 2, 3, 4, 5, 6, 7, 8, 9, 10","10")',
29
        'IncludesBoxOrCase' => "ENUM('No, Box, Case, Both','No')",
30
        'SellingOnBehalf' => 'Boolean',
31
        'OriginalManual' => 'Boolean',
32
        'DateItemWasBought' => 'Date',
33
        'DateItemWasSold' => 'Date',
34
        'SerialNumber' => 'Varchar(50)',
35
        'SellersName' =>  'Varchar(50)',
36
        'SellersPhone' =>  'Varchar(30)',
37
        'SellersEmail' =>  'Varchar(255)',
38
        'SellersAddress' =>  'Varchar(255)',
39
        'SellersAddress2' => 'Varchar(255)',
40
        'SellersCity' => 'Varchar(100)',
41
        'SellersPostalCode' => 'Varchar(50)',
42
        'SellersRegionCode' => 'Varchar(100)',
43
        'SellersCountry' => 'Varchar(50)',
44
        'SellersIDType' => 'ENUM(",Drivers Licence, Firearms Licence, Passport","")',
45
        'SellersIDNumber' => 'Varchar(50)',
46
        'SellersDateOfBirth' => 'Date',
47
        'SellersIDExpiryDate' => 'Date',
48
        'SellersIDPhotocopy' => 'Boolean'
49
    );
50
51
    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...
52
        'BasedOn' => 'SecondHandProduct'
53
    );
54
55
    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...
56
        'Created' => 'DESC'
57
    );
58
59
    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...
60
        'ShowInMenus' => false
61
    );
62
63
    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...
64
        'SerialNumber' => true
65
    );
66
67
    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...
68
        'SellersSummary' => 'Varchar',
69
        'CreatedNice' => 'Varchar'
70
    );
71
72
    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...
73
        'SellersName',
74
        'SellersPhone',
75
        'SellersEmail',
76
        'SellersAddress',
77
        'SellersAddress2',
78
        'SellersCity',
79
        'SellersPostalCode',
80
        'SellersRegionCode',
81
        'SellersCountry',
82
        'SellersIDType',
83
        'SellersIDNumber',
84
        'SellersDateOfBirth',
85
        'SellersIDExpiryDate',
86
        'SellersIDPhotocopy'
87
    );
88
89
    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...
90
        'FullName' => array(
91
            'title' => 'Keyword',
92
            'field' => 'TextField',
93
        ),
94
        'Price' => array(
95
            'title' => 'Price',
96
            'field' => 'NumericField',
97
        ),
98
        'InternalItemID' => array(
99
            'title' => 'Internal Item ID',
100
            'filter' => 'PartialMatchFilter',
101
        ),
102
        'SellersName' => array(
103
            'title' => 'Sellers Name',
104
            'filter' => 'PartialMatchFilter',
105
        ),
106
        'SellersPhone' => array(
107
            'title' => 'Sellers Phone',
108
            'filter' => 'PartialMatchFilter',
109
        ),
110
        'SellersEmail' => array(
111
            'title' => 'Sellers Email',
112
            'filter' => 'PartialMatchFilter',
113
        ),
114
        'AllowPurchase',
115
        'PurchasePrice' => 'ExactMatchFilter',
116
        'SerialNumber' => 'PartialMatchFilter'
117
    );
118
119
    public function getSellerSummary()
120
    {
121
        $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
122
        $array = array();
123
        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...
124
            if (trim($this->$field)) {
125
                $array[] = $this->$field;
126
            }
127
        }
128
        return implode('; ', $array);
129
    }
130
131
    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...
132
133
    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...
134
135
    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...
136
137
    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...
138
139
    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...
140
141
    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...
142
143
    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...
144
145
    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...
146
147
    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...
148
149
    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...
150
151
    /**
152
     * standard SS declaration
153
     * @var String
154
     */
155
    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...
156
157
    /**
158
     * Standard SS variable.
159
     */
160
    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...
161
    public function i18n_singular_name()
162
    {
163
        return self::$singular_name;
164
    }
165
166
    /**
167
     * Standard SS variable.
168
     */
169
    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...
170
    public function i18n_plural_name()
171
    {
172
        return self::$plural_name;
173
    }
174
175
    /**
176
     * standard SS declaration
177
     * @var String
178
     */
179
    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...
180
181
    /**
182
     * standard SS method
183
     * @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...
184
     */
185
    public function canCreate($member = null)
186
    {
187
        return Permission::check(
188
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
189
            'any',
190
            $member
191
        );
192
    }
193
194
    /**
195
     * standard SS method
196
     * @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...
197
     */
198
    public function canPublish($member = null)
199
    {
200
        return Permission::check(
201
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
202
            'any',
203
            $member
204
        );
205
    }
206
207
    /**
208
     * standard SS method
209
     * @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...
210
     */
211
    public function canEdit($member = null)
212
    {
213
        return Permission::check(
214
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
215
            'any',
216
            $member
217
        );
218
    }
219
220
    /**
221
     * standard SS method
222
     * @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...
223
     */
224
    public function canDelete($member = null)
225
    {
226
        return Permission::check(
227
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_code'),
228
            'any',
229
            $member
230
        );
231
    }
232
233
    public function onBeforeDelete()
234
    {
235
        if (Versioned::current_stage() !== 'Stage') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
236
            //do nothing
237
        } else {
238
            //page is being deleted permanently so create archived version
239
            SecondHandArchive::create_from_page($this);
240
        }
241
        parent::onBeforeDelete();
242
    }
243
244
245
    /**
246
     * stadard SS method
247
     * @return FieldList
248
     */
249
    public function getCMSFields()
250
    {
251
        $fields = parent::getCMSFields();
252
        //remove all unneccessary fields and tabs
253
        $fields->removeByName("AlsoShowHere");
254
        $fields->removeByName("Tax");
255
        $fields->removeByName("Links");
256
        $fields->removeByName("Details");
257
        $fields->removeByName("Images");
258
        $fields->removeFieldFromTab('Root', 'Title');
259
        $fields->removeFieldFromTab('Root', 'URLSegment');
260
        $fields->removeFieldFromTab('Root', 'MenuTitle');
261
        $fields->removeFieldFromTab('Root', 'ShortDescription');
262
        $fields->removeFieldFromTab('Root', 'Content');
263
        $fields->removeFieldFromTab('Root', 'Metadata');
264
        $fields->removeFieldFromTab('Root', 'AddToCartLink');
265
266
267
        $fields->addFieldsToTab(
268
            'Root.Main',
269
            array(
270
                $allowPurchaseField = CheckboxField::create("AllowPurchase", "<strong>Allow product to be purchased</strong>"),
271
                $sellinOnBehalf = CheckboxField::create("SellingOnBehalf", "<strong>Selling on behalf</strong>"),
272
                $featuredProductField = CheckboxField::create('FeaturedProduct', _t('Product.FEATURED', '<strong>Featured Product</strong>')),
273
                TextField::create('Title', 'Product Title'),
274
            )
275
        );
276
        $secondhandProductCategories = SecondHandProductGroup::get();
277
        if ($secondhandProductCategories->count()) {
278
            $fields->addFieldToTab(
279
                'Root.Main',
280
                $categoryField = DropdownField::create(
281
                    'ParentID',
282
                    'Product Category',
283
                    $secondhandProductCategories->map()
284
                )
285
            );
286
        }
287
        $fields->addFieldsToTab(
288
            'Root.Main',
289
            array(
290
                ReadonlyField::create('CanBeSold', "For Sale", DBField::create_field('Boolean', $this->canPurchase())->Nice()),
291
                ReadonlyField::create('CreatedNice', "First Entered", $this->getCreatedNice()),
292
                TextField::create('InternalItemID', "Product Code"),
293
                $purchasePriceField = NumericField::create('PurchasePrice', 'Purchase Price'),
294
                $salePriceField = NumericField::create('Price', 'Sale Price'),
295
                $soldPriceField = NumericField::create('SoldPrice', 'Sold Price'),
296
                $serialNumberField = TextField::create('SerialNumber', 'Serial Number'),
297
                $productQualityField = DropdownField::create(
298
                    "ProductQuality",
299
                    "Product Condition/Quality",
300
                    $this->dbObject('ProductQuality')->enumValues()
301
                ),
302
                $boxOrCaseField = DropdownField::create(
303
                    "IncludesBoxOrCase",
304
                    "Includes Box/Case",
305
                    $this->dbObject('IncludesBoxOrCase')->enumValues()
306
                ),
307
                $originalManualField = CheckboxField::create("OriginalManual", "Includes Original Manual"),
308
                $contentField = TextField::create("ShortDescription", "Description"),
309
                $boughtDate = DateField::create('DateItemWasBought', 'Date this item was bought'),
310
                $soldDate = DateField::create('DateItemWasSold', 'Date this item was sold'),
311
                $mainImageField = UploadField::create("Image", "Main Product Image"),
312
                $additionalImagesField = UploadField::create("AdditionalImages", "More Images"),
313
                $metaFieldDesc = TextareaField::create("MetaDescription", 'Meta Description')
314
            )
315
        );
316
        $soldDate->setDisabled(true);
317
318
        //set right titles and descriptions
319
        $featuredProductField->setDescription('If this box is ticked then this product will appear in the "Featured Products" box on the home page');
320
        $allowPurchaseField->setDescription("This box must be ticked to allow a customer to purchase it");
321
        $sellinOnBehalf->setDescription('This box must be ticked if this product is being sold on behalf');
322
        $purchasePriceField->setRightTitle("Price paid for the product");
323
        $salePriceField->setRightTitle("Selling price");
324
        $soldPriceField->setRightTitle("The price that the product actually sold for");
325
        $serialNumberField->setRightTitle("Enter the serial number of the product here");
326
        $originalManualField->setDescription("Tick this box if the product includes the original manual, otherwise leave it empty");
327
        $boxOrCaseField->setRightTitle("Does this product come with a box, case or both?");
328
        $contentField->setRightTitle("Optional text only description, the maximum length of this description is 255 characters.");
329
        $contentField->setMaxLength(255);
330
        $qualityFieldDescription = "A <strong>Condition Rating Page</strong> has yet to be setup";
331
        $obj = $this->EcomConfig()->SecondHandExplanationPage();
332
        if ($obj->exists()) {
333
            $qualityFieldDescription = 'An explanation of the ratings scale can be found by clicking this <a href="' . $obj->Link() . '">link</a>';
334
        }
335
        $productQualityField->setRightTitle($qualityFieldDescription);
336
        $boughtDate->setRightTitle('Date Format (dd-mm-YYYY). Example: 3rd of May 1992 should be entered as 03-05-1992');
337
        $mainImageField->setRightTitle(
338
            "<strong>Upload the main image for the product here.</strong><br>
339
            Recommended size: 810px wide x 418px high - but you can choose any width up to 810px, height must
340
            ALWAYS BE 418px. Should be provided to FTP data upload as productcode.jpg - e.g. 1003040.jpg.
341
            Images should be compressed up to 50%."
342
        );
343
        $additionalImagesField->setRightTitle(
344
            "<strong>Upload additional images here, you can upload as many as you want.</strong><br>
345
            Recommended size: 810px wide x 418px high - but you can choose any width up to 810px, height must
346
            ALWAYS BE 418px. Should be provided to FTP data upload as productcode.jpg - e.g. 1003040.jpg.
347
            Images should be compressed up to 50%."
348
        );
349
        //replace InternalItemID field with a read only field
350
        $fields->replaceField(
351
            'InternalItemID',
352
            $fields->dataFieldByName('InternalItemID')->performReadonlyTransformation()
353
        );
354
355
        $lastEditedItems = SecondHandProduct::get()->sort('Created', 'DESC')->limit(100);
356
357
        $lastItems = array(
358
            0 => '--- not based on previous sale ---'
359
        );
360
361
        foreach ($lastEditedItems as $lastEditedItem) {
362
            $details = $lastEditedItem->getSellerSummary();
363
            if ($details) {
364
                $lastItems[$lastEditedItem->ID] = $details;
365
            }
366
        }
367
368
        $fields->addFieldsToTab(
369
            'Root.SellersDetails',
370
            array(
371
                HeaderField::create('SellersDetails', 'Enter the details of the person who the product was purchased from'),
372
                DropdownField::create(
373
                    'BasedOnID',
374
                    'Autocomplete from saved items',
375
                    $lastItems
376
                ),
377
                TextField::create('SellersName', 'Name'),
378
                TextField::create('SellersPhone', 'Phone'),
379
                TextField::create('SellersEmail', 'Email Address'),
380
                DropdownField::create(
381
                    'SellersIDType',
382
                    'ID Type',
383
                    $this->dbObject('SellersIDType')->enumValues()
384
                ),
385
                TextField::create('SellersIDNumber', 'ID Number'),
386
                DateField::create('SellersDateOfBirth', 'Date of Birth'),
387
                DateField::create('SellersIDExpiryDate', 'ID Expiry Date'),
388
                CheckboxField::create('SellersIDPhotocopy', 'ID Photocopy')
389
            )
390
        );
391
392
        if (class_exists('GoogleAddressField')) {
393
            $mappingArray = $this->Config()->get('fields_to_google_geocode_conversion');
394
            if (is_array($mappingArray) && count($mappingArray)) {
395
                $fields->addFieldToTab(
396
                    'Root.SellersDetails',
397
                    $geocodingField = new GoogleAddressField(
398
                        'SellersAddressGeocodingField',
399
                        _t('OrderAddress.FIND_ADDRESS', 'Find address'),
400
                        Session::get('SellersAddressGeocodingFieldValue')
401
                    )
402
                );
403
                $geocodingField->setFieldMap($mappingArray);
404
405
                $country_code = Config::inst()->get('SecondHandProduct', 'country_code');
406
                if ($country_code) {
407
                    $geocodingField->setRestrictToCountryCode($country_code);
408
                }
409
                //$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...
410
            }
411
        }
412
413
        $fields->addFieldsToTab(
414
            'Root.SellersDetails',
415
            array(
416
                TextField::create('SellersAddress', 'Address'),
417
                TextField::create('SellersAddress2', 'Suburb'),
418
                TextField::create('SellersCity', 'City/Town'),
419
                TextField::create('SellersPostalCode', 'Postal Code'),
420
                TextField::create('SellersRegionCode', 'Region Code'),
421
                TextField::create('SellersCountry', 'Country'),
422
            )
423
        );
424
        //add all fields to the main tab
425
        $fields->addFieldToTab(
426
            'Root.SellersDetails',
427
            EcommerceCMSButtonField::create(
428
                'PrintView',
429
                $this->getPrintLink(),
430
                'Print Details',
431
                $newWindow = true
432
            )
433
        );
434
        if ($this->BasedOnID) {
435
            $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
436
            $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...
437
            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...
438
                $fields->replaceField(
439
                    $listField,
440
                    ReadonlyField::create(
441
                        $listField,
442
                        $fields->dataFieldByName($listField)->Title()
443
                    )
444
                );
445
            }
446
            $fields->removeByName('SellersAddressGeocodingField');
447
        }
448
        $fields->addFieldToTab(
449
            'Root.Categorisation',
450
            $categoriesTable = $this->getProductGroupsTableField()
451
        );
452
453
        // If the product has been sold all fields should be disabled
454
        // Only the shop administrator is allowed to undo this.
455
        if ($this->HasBeenSold()) {
456
            $fields->insertAfter(
457
                'AllowPurchase',
458
                EcommerceCMSButtonField::create(
459
                    'ArchiveButton',
460
                    '/admin/secondhandproducts/SecondHandProduct/archive/?productid=' . $this->ID,
461
                    _t('SecondHandProduct.ARCHIVE_BUTTON', 'Archive Product')
462
                )
463
            );
464
            $fields = $fields->makeReadonly();
465
            $fields->replaceField($categoriesTable->Name, $categoriesTable);
466
            $categoriesTable->setConfig(GridFieldConfig_RecordViewer::create());
467
            $fields->replaceField(
468
                'EnquiresList',
469
                GridField::create(
470
                    'EnquiresList',
471
                    'Enquiries List',
472
                    $this->PageEnquiries(),
473
                    GridFieldConfig_RecordViewer::create()
474
                )
475
            );
476
        }
477
478
        if ($this->canEdit()) {
479
            $fields->replaceField('AllowPurchase', CheckboxField::create('AllowPurchase', '<strong>Allow product to be purchased</strong>'));
480
            $fields->replaceField('DateItemWasSold', DateField::create('DateItemWasSold', 'Date this item was sold'));
481
        }
482
483
        return $fields;
484
    }
485
486
    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...
487
    {
488
        return $this->link('printview');
489
    }
490
491
    public function CMSEditLink()
492
    {
493
        return Controller::join_links(
494
            singleton('SecondHandProductAdmin')->Link(),
495
            $this->ClassName,
496
            'EditForm',
497
            'field',
498
            $this->ClassName,
499
            'item',
500
            $this->ID,
501
            'edit'
502
        );
503
    }
504
505
    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...
506
    {
507
        $fields = parent::getSettingsFields();
508
        $fields->removeByName('ParentID');
509
        return $fields;
510
    }
511
512
    public function canPurchase(Member $member = null, $checkPrice = true)
513
    {
514
        if ($this->HasBeenSold()) {
515
            return false;
516
        }
517
        $embargoDays = Config::inst()->get('SecondHandProduct', 'embargo_number_of_days');
518
        if (intval($embargoDays) > 0) {
519
            if ($this->DateItemWasBought) {
520
                $date = $this->DateItemWasBought;
521
            } else {
522
                $date = $this->Created;
523
            }
524
            $createdDate = strtotime($date);
525
            $daysOld = (time() - $createdDate) / (60 * 60 * 24);
526
            if ($daysOld <= $embargoDays) {
527
                return false;
528
            }
529
        }
530
        return parent::canPurchase($member, $checkPrice);
531
    }
532
533
    public function HasBeenSold()
534
    {
535
        if (parent::HasBeenSold()) {
536
            return true;
537
        }
538
        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...
539
            return true;
540
        }
541
        return false;
542
    }
543
544
    public function onBeforeWrite()
545
    {
546
        if ($this->BasedOnID) {
547
            $basedOn = $this->BasedOn();
548
            if ($basedOn && $basedOn->exists()) {
549
                $list = Config::inst()->get('SecondHandProduct', 'seller_summary_detail_fields');
550
                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...
551
                    $this->$field = $basedOn->$field;
552
                }
553
            }
554
        }
555
        $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...
556
557
        //set the IternatlItemID if it doesn't already exist
558
        if (! $this->InternalItemID) {
559
            //todo - this may need improvement
560
            $this->InternalItemID = "S-H-".strtoupper(substr(md5(microtime()), rand(0, 26), 5));
561
        }
562
        $this->URLSegment = $this->generateURLSegment($this->Title."-".$this->InternalItemID);
563
564
        if ($this->Title && strlen($this->MetaDescription) < 30) {
565
            $this->MetaDescription = "Second Hand Product: " . $this->Title;
566
        }
567
568
        // Save the date when the product was sold.
569
        if ($this->HasBeenSold()) {
570
            if (! $this->DateItemWasSold) {
571
                $this->DateItemWasSold = SS_Datetime::now()->Rfc2822();
572
            }
573
        }
574
        parent::onBeforeWrite();
575
    }
576
577
    public function SecondHandProductQualityPercentage()
578
    {
579
        return $this->ProductQuality * 10;
580
    }
581
582
    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...
583
    {
584
        return $this->InternalItemID;
585
    }
586
587
    public function providePermissions()
588
    {
589
        $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...
590
            'name' => EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_title'),
591
            'category' => 'E-commerce',
592
            'help' => EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_permission_help'),
593
            'sort' => 250,
594
        );
595
        return $perms;
596
    }
597
598
    public function requireDefaultRecords()
599
    {
600
        parent::requireDefaultRecords();
601
        $permissionProviderFactory = Injector::inst()->get('PermissionProviderFactory');
602
        $member = $permissionProviderFactory->CreateDefaultMember(
603
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_email'),
604
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_firstname'),
605
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_surname'),
606
            EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_user_password')
607
        );
608
        $permissionProviderFactory->CreateGroup(
609
            $code = EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_group_code'),
610
            $name = EcommerceConfig::get('SecondHandProduct', 'second_hand_admin_group_name'),
611
            $parentGroup = null,
612
            $permissionCode = EcommerceConfig::get(
613
                'SecondHandProduct',
614
                'second_hand_admin_permission_code'
615
            ),
616
            $roleTitle = EcommerceConfig::get(
617
                'SecondHandProduct',
618
                'second_hand_admin_permission_title'
619
            ),
620
            $permissionArray = array(
621
                'SITETREE_VIEW_ALL',
622
                'CMS_ACCESS_SecondHandProductAdmin',
623
            ),
624
            $member
625
        );
626
    }
627
628
    public function onAferSubmit($order)
629
    {
630
        DB::query('Update \"Product\" SET AllowPurchase = 0 WHERE \"Product\".\"ID\" = '.$this->ID);
631
        DB::query('Update \"Product_Live\" SET AllowPurchase = 0 WHERE \"Product_Live\".\"ID\" = '.$this->ID);
632
        $this->writeToStage('Stage');
633
        $this->doPublish();
634
    }
635
636
637
    /**
638
     * adds created as a summary field as we are sorting by created
639
     * @return array
640
     */
641
    public function summaryFields()
642
    {
643
        $fields = parent::summaryFields();
644
        $fields['CreatedNice'] = 'Entered';
645
        return $fields;
646
    }
647
648
649
    public function populateDefaults()
650
    {
651
        parent::populateDefaults();
652
        if (! $this->DateItemWasBought) {
653
            $this->DateItemWasBought = SS_Datetime::now()->Rfc2822();
654
        }
655
    }
656
657
658
    public function getCreatedNice()
659
    {
660
        if ($this->DateItemWasBought) {
661
            $date = $this->DateItemWasBought;
662
        } else {
663
            $date = $this->Created;
664
        }
665
        return $date.' = '.DBField::create_field('Date', $date)->Ago();
666
    }
667
}
668
669
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...
670
{
671
    private static $fields_to_remove_from_print = array();
672
673
    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...
674
        'printview' => true
675
    );
676
677
    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...
678
    {
679
        if (!Permission::check('CMS_ACCESS_SECOND_HAND_PRODUCTS')) {
680
            return Security::permissionFailure($this, 'You do not have access to this feature, please login first.');
681
        }
682
        return $this->renderWith('SecondHandProduct_printview');
683
    }
684
685
    public function ListOfFieldsForPrinting()
686
    {
687
        $al = ArrayList::create();
688
        $fieldsWeNeed = $this->dataRecord->stat('db');
689
        $labels = $this->FieldLabels();
690
        foreach ($fieldsWeNeed as $fieldKey => $useless) {
691
            if (in_array($fieldKey, self::$fields_to_remove_from_print)) {
692
                unset($fieldsWeNeed[$fieldKey]);
693
            } else {
694
                $fieldsWeNeed[$fieldKey] = $labels[$fieldKey];
695
            }
696
        }
697
        $fields = $this->dataRecord->db();
698
        foreach ($fieldsWeNeed as $key => $description) {
699
            if (isset($fields[$key])) {
700
                $type = preg_replace('/\(.*\)/', '', $fields[$key]);
701
                $dbField = DBField::create_field($type, $this->$key);
702
                if ($dbField->hasMethod('Nice')) {
703
                    $value = $dbField->Nice();
704
                } else {
705
                    $value = $dbField->Raw();
706
                }
707
            } else {
708
                $value = "";
709
            }
710
            $al->push(
711
                ArrayData::create(
712
                    array(
713
                        'Key' => $description,
714
                        'Value' => $value
715
                    )
716
                )
717
            );
718
        }
719
        return $al;
720
    }
721
}
722