Passed
Pull Request — master (#309)
by Jason
06:15 queued 01:51
created

ProductCategory::getCMSFields()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 115
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 53
CRAP Score 3.0013

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 115
ccs 53
cts 56
cp 0.9464
rs 8.2857
cc 3
eloc 55
nc 3
nop 0
crap 3.0013

How to fix   Long Method   

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
namespace Dynamic\FoxyStripe\Model;
4
5
use SilverStripe\Forms\DropdownField;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\Forms\HeaderField;
8
use SilverStripe\Forms\OptionsetField;
9
use SilverStripe\Forms\ReadonlyField;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\Security\Permission;
12
13
class ProductCategory extends DataObject
14
{
15
    /**
16
     * @var array
17
     */
18
    private static $db = array(
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
19
        'Title' => 'Varchar(255)',
20
        'Code' => 'Varchar(50)',
21
        'DeliveryType' => 'Varchar(50)',
22
        'MaxDownloads' => 'Int',
23
        'MaxDownloadsTime' => 'Int',
24
        'DefaultWeight' => 'Float',
25
        'DefaultWeightUnit' => 'Enum("LBS, KBS", "LBS")',
26
        'DefaultLengthUnit' => 'Enum("in, cm", "in")',
27
        'ShippingFlatRate' => 'Currency',
28
        'ShippingFlatRateType' => 'Varchar(50)',
29
        'HandlingFeeType' => 'Varchar(50)',
30
        'HandlingFee' => 'Currency',
31
        'HandlingFeePercentage' => 'Decimal',
32
        'HandlingFeeMinimum' => 'Currency',
33
        'DiscountType' => 'Varchar(50)',
34
        'DiscountName' => 'Varchar(50)',
35
        'DiscountDetails' => 'Varchar(200)',
36
        'CustomsValue' => 'Currency',
37
    );
38
39
    /**
40
     * @var string
41
     */
42
    private static $singular_name = 'FoxyCart Category';
0 ignored issues
show
introduced by
The private property $singular_name is not used, and could be removed.
Loading history...
43
44
    /**
45
     * @var string
46
     */
47
    private static $plural_name = 'FoxyCart Categories';
0 ignored issues
show
introduced by
The private property $plural_name is not used, and could be removed.
Loading history...
48
49
    /**
50
     * @var string
51
     */
52
    private static $description = 'Set the FoxyCart Category on a Product';
0 ignored issues
show
introduced by
The private property $description is not used, and could be removed.
Loading history...
53
54
    /**
55
     * @var array
56
     */
57
    private static $summary_fields = array(
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
58
        'Title' => 'Name',
59
        'Code' => 'Code',
60
    );
61
62
    /**
63
     * @var array
64
     */
65
    private static $indexes = array(
0 ignored issues
show
introduced by
The private property $indexes is not used, and could be removed.
Loading history...
66
        'Code' => true,
67
    );
68
69
    /**
70
     * @var string
71
     */
72
    private static $table_name = 'FS_ProductCategory';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
73
74
    /**
75
     * @return FieldList
76
     */
77 1
    public function getCMSFields()
78
    {
79 1
        $fields = parent::getCMSFields();
80
81 1
        if ($this->ID) {
82 1
            if ($this->Title == 'Default') {
83
                $fields->replaceField(
84
                    'Title',
85
                    ReadonlyField::create('Title')
0 ignored issues
show
Bug introduced by
'Title' of type string is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

85
                    ReadonlyField::create(/** @scrutinizer ignore-type */ 'Title')
Loading history...
86
                );
87
            }
88
89 1
            $fields->replaceField(
90 1
                'Code',
91 1
                ReadonlyField::create('Code')
92
            );
93
        }
94
95 1
        $fields->insertBefore(HeaderField::create('DeliveryHD', 'Delivery Options', 3), 'DeliveryType');
0 ignored issues
show
Bug introduced by
'DeliveryType' of type string is incompatible with the type SilverStripe\Forms\FormField expected by parameter $item of SilverStripe\Forms\FieldList::insertBefore(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
        $fields->insertBefore(HeaderField::create('DeliveryHD', 'Delivery Options', 3), /** @scrutinizer ignore-type */ 'DeliveryType');
Loading history...
Bug introduced by
3 of type integer is incompatible with the type array expected by parameter $args of SilverStripe\View\ViewableData::create(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
        $fields->insertBefore(HeaderField::create('DeliveryHD', 'Delivery Options', /** @scrutinizer ignore-type */ 3), 'DeliveryType');
Loading history...
96
97 1
        $fields->replaceField(
98 1
            'DeliveryType',
99 1
            OptionsetField::create('DeliveryType', 'Delivery Type', $this->getShippingOptions())
100
        );
101
102 1
        $fields->dataFieldByName('MaxDownloads')
103 1
            ->displayIf('DeliveryType')->isEqualTo('downloaded');
104
105 1
        $fields->dataFieldByName('MaxDownloadsTime')
106 1
            ->displayIf('DeliveryType')->isEqualTo('downloaded');
107
108 1
        $fields->dataFieldByName('DefaultWeight')
109 1
            ->displayIf('DeliveryType')->isEqualTo('shipped');
110
111 1
        $fields->dataFieldByName('DefaultWeightUnit')
112 1
            ->displayIf('DeliveryType')->isEqualTo('shipped');
113
114 1
        $fields->dataFieldByName('DefaultLengthUnit')
115 1
            ->displayIf('DeliveryType')->isEqualTo('shipped');
116
117 1
        $fields->dataFieldByName('ShippingFlatRate')
118 1
            ->displayIf('DeliveryType')->isEqualTo('flat_rate');
119
120 1
        $fields->replaceField(
121 1
            'ShippingFlatRateType',
122 1
            DropdownField::create('ShippingFlatRateType', 'Flat Rate Type', $this->getShippingFlatRateTypes())
123 1
                ->setEmptyString('')
124 1
                ->displayIf('DeliveryType')->isEqualTo('flat_rate')->end()
125
        );
126
127 1
        $fields->insertBefore(HeaderField::create('HandlingHD', 'Handling Fees and Discounts', 3), 'HandlingFeeType');
128
129 1
        $fields->replaceField(
130 1
            'HandlingFeeType',
131 1
            DropdownField::create('HandlingFeeType', 'Handling Fee Type', $this->getHandlingFeeTypes())
132 1
                ->setEmptyString('')
133 1
                ->setDescription('This determines what type of Handling Fee you would like to use.')
134
        );
135
136 1
        $fields->dataFieldByName('HandlingFee')
137 1
            ->displayIf('HandlingFeeType')->isNotEqualTo('');
138
139 1
        $fields->dataFieldByName('HandlingFeeMinimum')
140 1
            ->displayIf('HandlingFeeType')->isEqualTo('flat_percent_with_minimum');
141
142 1
        $fields->dataFieldByName('HandlingFeePercentage')
143 1
            ->displayIf('HandlingFeeType')->isEqualTo('flat_percent_with_minimum')
144 1
            ->orIf('HandlingFeeType')->isEqualTo('flat_percent');
145
146 1
        $fields->replaceField(
147 1
            'DiscountType',
148 1
            DropdownField::create('DiscountType', 'Discount Type', $this->getDiscountTypes())
149 1
                ->setEmptyString('')
150 1
                ->setDescription('This determines what type of per category discount you would like to use, if any.')
151
        );
152
153 1
        $fields->dataFieldByName('DiscountName')
154 1
            ->displayIf('DiscountType')->isNotEqualTo('');
155
156 1
        $fields->dataFieldByName('DiscountDetails')
157 1
            ->displayIf('DiscountType')->isNotEqualTo('');
158
159 1
        $fields->dataFieldByName('CustomsValue')
160 1
            ->setDescription('Enter a dollar amount here for the declared customs value for international shipments. If you leave this blank, the sale price of the item will be used.');
161
162
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
163
        $fields = FieldList::create(
164
            LiteralField::create(
165
                'PCIntro',
166
                _t(
167
                    'ProductCategory.PCIntro',
168
                    '<p>Categories must be created in your
169
                        <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">
170
                            FoxyCart Product Categories
171
                        </a>, and also manually created in FoxyStripe.
172
                    </p>'
173
                )
174
            ),
175
            TextField::create('Code')
176
                ->setTitle(_t('ProductCategory.Code', 'Category Code'))
177
                ->setDescription(_t('ProductCategory.CodeDescription', 'copy/paste from FoxyCart')),
178
            TextField::create('Title')
179
                ->setTitle(_t('ProductCategory.Title', 'Category Title'))
180
                ->setDescription(_t('ProductCategory.TitleDescription', 'copy/paste from FoxyCart')),
181
            DropdownField::create(
182
                'DeliveryType',
183
                'Delivery Type',
184
                singleton('ProductCategory')->dbObject('DeliveryType')->enumValues()
185
            )->setEmptyString('')
186
        );
187
188
        $this->extend('updateCMSFields', $fields);
189
        */
190
191 1
        return $fields;
192
    }
193
194
    /**
195
     * @throws \SilverStripe\ORM\ValidationException
196
     */
197
    public function requireDefaultRecords()
198
    {
199
        parent::requireDefaultRecords();
200
        $allCats = self::get();
201
        if (!$allCats->count()) {
202
            $cat = new self();
203
            $cat->Title = 'Default';
0 ignored issues
show
Bug Best Practice introduced by
The property Title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
204
            $cat->Code = 'DEFAULT';
0 ignored issues
show
Bug Best Practice introduced by
The property Code does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
205
            $cat->write();
206
        }
207
    }
208
209
    /**
210
     * @param bool $member
211
     *
212
     * @return bool
213
     */
214 49
    public function canView($member = false)
215
    {
216 49
        return true;
217
    }
218
219
    /**
220
     * @param null $member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $member is correct as it would always require null to be passed?
Loading history...
221
     *
222
     * @return bool|int
223
     */
224 1
    public function canEdit($member = null)
225
    {
226 1
        return Permission::check('Product_CANCRUD', 'any', $member);
227
    }
228
229
    /**
230
     * @param null $member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $member is correct as it would always require null to be passed?
Loading history...
231
     *
232
     * @return bool|int
233
     */
234 2
    public function canDelete($member = null)
235
    {
236
237
        //don't allow deletion of DEFAULT category
238 2
        return ($this->Code == 'DEFAULT') ? false : Permission::check('Product_CANCRUD', 'any', $member);
239
    }
240
241
    /**
242
     * @param null $member
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $member is correct as it would always require null to be passed?
Loading history...
243
     *
244
     * @return bool|int
245
     */
246 1
    public function canCreate($member = null, $context = [])
247
    {
248 1
        return Permission::check('Product_CANCRUD', 'any', $member);
249
    }
250
251
    /**
252
     * @return array
253
     */
254 2
    public function getShippingOptions()
255
    {
256
        return [
257 2
            'shipped' => 'Shipped using live shipping rates',
258
            'downloaded' => 'Downloaded by the customer',
259
            'flat_rate' => 'Shipped using a flat rate fee',
260
            'pickup' => 'Picked up by the customer',
261
            'notshipped' => 'No Shipping',
262
        ];
263
    }
264
265
    /**
266
     * @return array
267
     */
268 2
    public function getShippingFlatRateTypes()
269
    {
270
        return [
271 2
            'per_order' => 'Charge per order',
272
            'per_item' => 'Charge per item',
273
        ];
274
    }
275
276
    /**
277
     * @return array
278
     */
279 2
    public function getHandlingFeeTypes()
280
    {
281
        return [
282 2
            'flat_per_order' => 'Flat fee per order with products in this category',
283
            'flat_per_item' => 'Flat fee per product in this category',
284
            'flat_percent' => 'Flat fee per shipment + % of price for products in this category',
285
            'flat_percent_with_minimum' => 'Flat fee per shipment OR % of order total with products in this category. Whichever is greater.',
286
        ];
287
    }
288
289
    /**
290
     * @return array
291
     */
292 2
    public function getDiscountTypes()
293
    {
294
        return [
295 2
            'quantity_amount' => 'Discount by an amount based on the quantity',
296
            'quantity_percentage' => 'Discount by a percentage based on the quantity',
297
            'price_amount' => 'Discount by an amount based on the price in this category',
298
            'price_percentage' => 'Discount by a percentage based on the price in this category',
299
        ];
300
    }
301
302
    /**
303
     * @return array
304
     */
305 49
    public function getDataMap()
306
    {
307
        return [
308 49
            'name' => $this->Title,
309 49
            'code' => $this->Code,
310 49
            'item_delivery_type' => $this->DeliveryType,
0 ignored issues
show
Bug Best Practice introduced by
The property DeliveryType does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
311 49
            'max_downloads_per_customer' => $this->MaxDownloads,
0 ignored issues
show
Bug Best Practice introduced by
The property MaxDownloads does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
312 49
            'max_downloads_time_period' => $this->MaxDownloadsTime,
0 ignored issues
show
Bug Best Practice introduced by
The property MaxDownloadsTime does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
313 49
            'customs_value' => $this->CustomsValue,
0 ignored issues
show
Bug Best Practice introduced by
The property CustomsValue does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
314 49
            'default_weight' => $this->DefaultWeight,
0 ignored issues
show
Bug Best Practice introduced by
The property DefaultWeight does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
315 49
            'default_weight_unit' => $this->DefaultWeightUnit,
0 ignored issues
show
Bug Best Practice introduced by
The property DefaultWeightUnit does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
316 49
            'default_length_unit' => $this->DefautlLengthUnit,
0 ignored issues
show
Bug Best Practice introduced by
The property DefautlLengthUnit does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
317 49
            'shipping_flat_rate' => $this->ShippingFlatRate,
0 ignored issues
show
Bug Best Practice introduced by
The property ShippingFlatRate does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
318 49
            'shipping_flat_rate_type' => $this->ShippingFlatRateType,
0 ignored issues
show
Bug Best Practice introduced by
The property ShippingFlatRateType does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
319 49
            'handling_fee_type' => $this->HandlingFeeType,
0 ignored issues
show
Bug Best Practice introduced by
The property HandlingFeeType does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
320 49
            'handling_fee' => $this->HandlingFee,
0 ignored issues
show
Bug Best Practice introduced by
The property HandlingFee does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
321 49
            'handling_fee_minimum' => $this->HandlingFeeMinimum,
0 ignored issues
show
Bug Best Practice introduced by
The property HandlingFeeMinimum does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
322 49
            'handling_fee_percentage' => $this->HandlingFeePercentage,
0 ignored issues
show
Bug Best Practice introduced by
The property HandlingFeePercentage does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
323 49
            'discount_type' => $this->DiscountType,
0 ignored issues
show
Bug Best Practice introduced by
The property DiscountType does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
324 49
            'discount_name' => $this->DiscountName,
0 ignored issues
show
Bug Best Practice introduced by
The property DiscountName does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
325 49
            'discount_details' => $this->DiscountDetails,
0 ignored issues
show
Bug Best Practice introduced by
The property DiscountDetails does not exist on Dynamic\FoxyStripe\Model\ProductCategory. Since you implemented __get, consider adding a @property annotation.
Loading history...
326
        ];
327
    }
328
329
    /**
330
     * @throws \Psr\Container\NotFoundExceptionInterface
331
     */
332 49
    public function onAfterWrite()
333
    {
334 49
        parent::onAfterWrite();
335
336 49
        if ($this->isChanged()) {
337 49
            if ($fc = new FoxyStripeClient()) {
338 49
                $fc->putCategory($this->getDataMap());
339
            }
340
        }
341
    }
342
343
    /**
344
     * @throws \Psr\Container\NotFoundExceptionInterface
345
     */
346 1
    public function onAfterDelete()
347
    {
348 1
        parent::onAfterDelete();
349
350 1
        if ($fc = new FoxyStripeClient()) {
351 1
            $fc->deleteCategory($this->getDataMap());
352
        }
353
    }
354
}
355