Completed
Push — master ( f8f77e...d2a4ab )
by Jason
05:01
created

ProductCategory::onAfterWrite()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 4
nc 3
nop 0
crap 3
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 
161
            shipments. If you leave this blank, the sale price of the item will be used.');
162
163
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
164
        $fields = FieldList::create(
165
            LiteralField::create(
166
                'PCIntro',
167
                _t(
168
                    'ProductCategory.PCIntro',
169
                    '<p>Categories must be created in your
170
                        <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories"
171
                            target="_blank">
172
                            FoxyCart Product Categories
173
                        </a>, and also manually created in FoxyStripe.
174
                    </p>'
175
                )
176
            ),
177
            TextField::create('Code')
178
                ->setTitle(_t('ProductCategory.Code', 'Category Code'))
179
                ->setDescription(_t('ProductCategory.CodeDescription', 'copy/paste from FoxyCart')),
180
            TextField::create('Title')
181
                ->setTitle(_t('ProductCategory.Title', 'Category Title'))
182
                ->setDescription(_t('ProductCategory.TitleDescription', 'copy/paste from FoxyCart')),
183
            DropdownField::create(
184
                'DeliveryType',
185
                'Delivery Type',
186
                singleton('ProductCategory')->dbObject('DeliveryType')->enumValues()
187
            )->setEmptyString('')
188
        );
189
190
        $this->extend('updateCMSFields', $fields);
191
        */
192
193 1
        return $fields;
194
    }
195
196
    /**
197
     * @throws \SilverStripe\ORM\ValidationException
198
     */
199
    public function requireDefaultRecords()
200
    {
201
        parent::requireDefaultRecords();
202
        $allCats = self::get();
203
        if (!$allCats->count()) {
204
            $cat = new self();
205
            $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...
206
            $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...
207
            $cat->write();
208
        }
209
    }
210
211
    /**
212
     * @param bool $member
213
     *
214
     * @return bool
215
     */
216 49
    public function canView($member = false)
217
    {
218 49
        return true;
219
    }
220
221
    /**
222
     * @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...
223
     *
224
     * @return bool|int
225
     */
226 1
    public function canEdit($member = null)
227
    {
228 1
        return Permission::check('Product_CANCRUD', 'any', $member);
229
    }
230
231
    /**
232
     * @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...
233
     *
234
     * @return bool|int
235
     */
236 2
    public function canDelete($member = null)
237
    {
238
239
        //don't allow deletion of DEFAULT category
240 2
        return ($this->Code == 'DEFAULT') ? false : Permission::check('Product_CANCRUD', 'any', $member);
241
    }
242
243
    /**
244
     * @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...
245
     *
246
     * @return bool|int
247
     */
248 1
    public function canCreate($member = null, $context = [])
249
    {
250 1
        return Permission::check('Product_CANCRUD', 'any', $member);
251
    }
252
253
    /**
254
     * @return array
255
     */
256 2
    public function getShippingOptions()
257
    {
258
        return [
259 2
            'shipped' => 'Shipped using live shipping rates',
260
            'downloaded' => 'Downloaded by the customer',
261
            'flat_rate' => 'Shipped using a flat rate fee',
262
            'pickup' => 'Picked up by the customer',
263
            'notshipped' => 'No Shipping',
264
        ];
265
    }
266
267
    /**
268
     * @return array
269
     */
270 2
    public function getShippingFlatRateTypes()
271
    {
272
        return [
273 2
            'per_order' => 'Charge per order',
274
            'per_item' => 'Charge per item',
275
        ];
276
    }
277
278
    /**
279
     * @return array
280
     */
281 2
    public function getHandlingFeeTypes()
282
    {
283
        return [
284 2
            'flat_per_order' => 'Flat fee per order with products in this category',
285
            'flat_per_item' => 'Flat fee per product in this category',
286
            'flat_percent' => 'Flat fee per shipment + % of price for products in this category',
287
            'flat_percent_with_minimum' => 'Flat fee per shipment OR % of order total with products in this category. 
288
                Whichever is greater.',
289
        ];
290
    }
291
292
    /**
293
     * @return array
294
     */
295 2
    public function getDiscountTypes()
296
    {
297
        return [
298 2
            'quantity_amount' => 'Discount by an amount based on the quantity',
299
            'quantity_percentage' => 'Discount by a percentage based on the quantity',
300
            'price_amount' => 'Discount by an amount based on the price in this category',
301
            'price_percentage' => 'Discount by a percentage based on the price in this category',
302
        ];
303
    }
304
305
    /**
306
     * @return array
307
     */
308 49
    public function getDataMap()
309
    {
310
        return [
311 49
            'name' => $this->Title,
312 49
            'code' => $this->Code,
313 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...
314 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...
315 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...
316 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...
317 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...
318 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...
319 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...
320 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...
321 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...
322 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...
323 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...
324 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...
325 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...
326 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...
327 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...
328 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...
329
        ];
330
    }
331
332
    /**
333
     * @throws \Psr\Container\NotFoundExceptionInterface
334
     */
335 49
    public function onAfterWrite()
336
    {
337 49
        parent::onAfterWrite();
338
339 49
        if ($this->isChanged()) {
340 49
            if ($fc = new FoxyStripeClient()) {
341 49
                $fc->putCategory($this->getDataMap());
342
            }
343
        }
344
    }
345
346
    /**
347
     * @throws \Psr\Container\NotFoundExceptionInterface
348
     */
349 1
    public function onAfterDelete()
350
    {
351 1
        parent::onAfterDelete();
352
353 1
        if ($fc = new FoxyStripeClient()) {
354 1
            $fc->deleteCategory($this->getDataMap());
355
        }
356
    }
357
}
358