Passed
Pull Request — master (#93)
by Nic
03:28
created

Purchasable::updateCMSFields()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 77
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 55
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 77
rs 8.9818

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\Foxy\Extension;
4
5
use Dynamic\Foxy\Model\FoxyCategory;
6
use Dynamic\Foxy\Model\ProductOption;
7
use SilverStripe\Forms\CheckboxField;
8
use SilverStripe\Forms\CurrencyField;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Forms\FieldList;
11
use SilverStripe\Forms\GridField\GridField;
12
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
13
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
14
use SilverStripe\Forms\NumericField;
15
use SilverStripe\Forms\TextField;
16
use SilverStripe\ORM\DataExtension;
17
use SilverStripe\ORM\ValidationResult;
18
use SilverStripe\Security\Permission;
19
use SilverStripe\Security\PermissionProvider;
20
use SilverStripe\Security\Security;
21
use Symbiote\GridFieldExtensions\GridFieldAddExistingSearchButton;
22
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;
23
24
/**
25
 * Class Purchasable
26
 * @package Dynamic\Foxy\Extension
27
 *
28
 * @property double Price
29
 * @property string Code
30
 * @property string ReceiptTitle
31
 * @property bool Available
32
 *
33
 * @property int FoxyCategoryID
34
 * @method FoxyCategory FoxyCategory()
35
 *
36
 * @method \SilverStripe\ORM\ManyManyList Options()
37
 *
38
 * @property-read \SilverStripe\ORM\DataObject|Purchasable $owner
39
 */
40
class Purchasable extends DataExtension implements PermissionProvider
41
{
42
    /**
43
     * @var array
44
     */
45
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
46
        'Price' => 'Currency',
47
        'Code' => 'Varchar(100)',
48
        'ReceiptTitle' => 'HTMLVarchar(255)',
49
        'Available' => 'Boolean',
50
        'QuantityMax' => 'Int',
51
    ];
52
53
    /**
54
     * @var array
55
     */
56
    private static $has_one = [
0 ignored issues
show
introduced by
The private property $has_one is not used, and could be removed.
Loading history...
57
        'FoxyCategory' => FoxyCategory::class,
58
    ];
59
60
    /**
61
     * @var array
62
     */
63
    private static $many_many = [
0 ignored issues
show
introduced by
The private property $many_many is not used, and could be removed.
Loading history...
64
        'Options' => ProductOption::class,
65
    ];
66
67
    /**
68
     * @var array
69
     */
70
    private static $many_many_extraFields = [
0 ignored issues
show
introduced by
The private property $many_many_extraFields is not used, and could be removed.
Loading history...
71
        'Options' => [
72
            'WeightModifier' => 'Decimal(9,3)',
73
            'CodeModifier' => 'Text',
74
            'PriceModifier' => 'Currency',
75
            'WeightModifierAction' => "Enum('Add,Subtract,Set', null)",
76
            'CodeModifierAction' => "Enum('Add,Subtract,Set', null)",
77
            'PriceModifierAction' => "Enum('Add,Subtract,Set', null)",
78
            'Available' => 'Boolean',
79
            'Type' => 'Int',
80
            'OptionModifierKey' => 'Varchar(255)',
81
            'SortOrder' => 'Int',
82
        ],
83
        'OptionTypes' => [
84
            'SortOrder' => 'Int',
85
        ],
86
    ];
87
88
    /**
89
     * @var array
90
     */
91
    private static $indexes = [
0 ignored issues
show
introduced by
The private property $indexes is not used, and could be removed.
Loading history...
92
        'Code' => [
93
            'type' => 'unique',
94
            'columns' => ['Code'],
95
        ],
96
    ];
97
98
    /**
99
     * @var array
100
     */
101
    private static $defaults = [
0 ignored issues
show
introduced by
The private property $defaults is not used, and could be removed.
Loading history...
102
        'ShowInMenus' => false,
103
        'Available' => true,
104
    ];
105
106
    /**
107
     * @var array
108
     */
109
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
110
        'Image.CMSThumbnail',
111
        'Title',
112
        'Code',
113
        'Price.Nice',
114
    ];
115
116
    /**
117
     * @var array
118
     */
119
    private static $searchable_fields = [
0 ignored issues
show
introduced by
The private property $searchable_fields is not used, and could be removed.
Loading history...
120
        'Title',
121
        'Code',
122
        'Available',
123
    ];
124
125
    /**
126
     * @param bool $includerelations
127
     *
128
     * @return array
129
     */
130
    public function updateFieldLabels(&$labels)
131
    {
132
        $labels['Title'] = _t(__CLASS__ . '.TitleLabel', 'Product Name');
133
        $labels['Code'] = _t(__CLASS__ . '.CodeLabel', 'Code');
134
        $labels['Price'] = _t(__CLASS__ . '.PriceLabel', 'Price');
135
        $labels['Price.Nice'] = _t(__CLASS__ . '.PriceLabel', 'Price');
136
        $labels['Available'] = _t(__CLASS__ . '.AvailableLabel', 'Available for purchase');
137
        $labels['Available.Nice'] = _t(__CLASS__ . '.AvailableLabelNice', 'Available');
138
        $labels['Image.CMSThumbnail'] = _t(__CLASS__ . '.ImageLabel', 'Image');
139
        $labels['ReceiptTitle'] = _t(__CLASS__ . '.ReceiptTitleLabel', 'Product title for receipt');
140
        $labels['FoxyCategoryID'] = _t(__CLASS__ . '.FoxyCategoryLabel', 'Foxy Category');
141
    }
142
143
    /**
144
     * @param FieldList $fields
145
     */
146
    public function updateCMSFields(FieldList $fields)
147
    {
148
        $fields->removeByName([
149
            'SKU',
150
        ]);
151
152
        $fields->addFieldsToTab(
153
            'Root.Ecommerce',
154
            [
155
                CurrencyField::create('Price')
156
                    ->setDescription(_t(
157
                        __CLASS__ . '.PriceDescription',
158
                        'Base price for this product. Can be modified using Product Options'
159
                    )),
160
                TextField::create('Code')
161
                    ->setDescription(_t(
162
                        __CLASS__ . '.CodeDescription',
163
                        'Required, must be unique. Product identifier used by FoxyCart in transactions. All leading and trailing spaces are removed on save.'
164
                    )),
165
                DropdownField::create('FoxyCategoryID')
166
                    ->setTitle($this->owner->fieldLabel('FoxyCategoryID'))
0 ignored issues
show
Bug introduced by
The method fieldLabel() does not exist on Dynamic\Foxy\Extension\Purchasable. ( Ignorable by Annotation )

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

166
                    ->setTitle($this->owner->/** @scrutinizer ignore-call */ fieldLabel('FoxyCategoryID'))

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
167
                    ->setSource(FoxyCategory::get()->map())
168
                    ->setDescription(_t(
169
                        __CLASS__ . '.FoxyCategoryDescription',
170
                        'Required. Must also exist in
171
                        <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories"
172
                            target="_blank">
173
                            Foxy Categories
174
                        </a>.
175
                        Used to set category specific options like shipping and taxes. Managed in Foxy > Categories'
176
                    ))
177
                    ->setEmptyString(''),
178
                TextField::create('ReceiptTitle')
179
                    ->setDescription(_t(
180
                        __CLASS__ . '.ReceiptTitleDescription',
181
                        'Optional. Alternate title to display on order receipt'
182
                    )),
183
            ],
184
            'Content'
185
        );
186
187
        if ($this->owner->ID) {
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on Dynamic\Foxy\Extension\Purchasable. Did you maybe forget to declare it?
Loading history...
188
            $config = GridFieldConfig_RelationEditor::create();
189
            $config
190
                ->addComponents([
191
                    new GridFieldOrderableRows('SortOrder'),
192
                    new GridFieldAddExistingSearchButton(),
193
                ])
194
                ->removeComponentsByType([
195
                    GridFieldAddExistingAutocompleter::class,
196
                ]);
197
            $options = GridField::create(
198
                'Options',
199
                'Options',
200
                $this->owner->Options()->sort('SortOrder'),
201
                $config
202
            );
203
204
            $fields->addFieldsToTab(
205
                'Root.Options',
206
                [
207
                    $options,
208
                ]
209
            );
210
        }
211
212
        $fields->addFieldsToTab(
213
            'Root.Inventory',
214
            [
215
                NumericField::create('QuantityMax')
216
                    ->setTitle('Maximum quantity allowed in the cart')
217
                    ->setDescription('For unlimited enter 0')
218
                    ->addExtraClass('stacked'),
219
                CheckboxField::create('Available')
220
                    ->setDescription(_t(
221
                        __CLASS__ . '.AvailableDescription',
222
                        'If unchecked, will remove "Add to Cart" form and instead display "Currently unavailable"'
223
                    )),
224
            ]
225
        );
226
    }
227
228
    /**
229
     * @return \SilverStripe\ORM\ValidationResult
230
     */
231
    public function validate(ValidationResult $validationResult)
232
    {
233
        /*
234
        if (!$this->owner->Price) {
235
            $validationResult->addError(
236
                _t(__CLASS__ . '.PriceRequired', 'You must set a product price in the Foxy tab')
237
            );
238
        }
239
240
        if (!$this->owner->Code) {
241
            $validationResult->addError(
242
                _t(__CLASS__ . '.CodeRequired', 'You must set a product code in the Foxy tab')
243
            );
244
        }
245
246
        if (!$this->owner->FoxyCategoryID) {
247
            $validationResult->addError(
248
                _t(__CLASS__ . '.FoxyCategoryRequired', 'You must set a foxy category in the Foxy tab.')
249
            );
250
        }
251
        */
252
    }
253
254
    /**
255
     * @return bool
256
     */
257
    public function isAvailable()
258
    {
259
        if (!$this->owner->Available) {
260
            return false;
261
        }
262
263
        if (!$this->owner->Options()->exists()) {
264
            return true;
265
        }
266
267
        foreach ($this->owner->Options() as $option) {
268
            if ($option->Available) {
269
                return true;
270
            }
271
        }
272
273
        return false;
274
    }
275
276
    /**
277
     * @return bool
278
     */
279
    public function isProduct()
280
    {
281
        return true;
282
    }
283
284
    /**
285
     * @return array
286
     */
287
    public function providePermissions()
288
    {
289
        return [
290
            'MANAGE_FOXY_PRODUCTS' => [
291
                'name' => _t(
292
                    __CLASS__ . '.PERMISSION_MANAGE_PRODUCTS_DESCRIPTION',
293
                    'Manage products'
294
                ),
295
                'category' => _t(
296
                    __CLASS__ . '.PERMISSIONS_CATEGORY',
297
                    'Foxy'
298
                ),
299
                'help' => _t(
300
                    __CLASS__ . '.PERMISSION_MANAGE_PRODUCTS_HELP',
301
                    'Manage products and related settings'
302
                ),
303
                'sort' => 400,
304
            ],
305
        ];
306
    }
307
308
    /**
309
     * @param $member
310
     * @return bool|int|void
311
     */
312
    public function canCreate($member)
313
    {
314
        if (!$member) {
315
            $member = Security::getCurrentUser();
316
        }
317
318
        return Permission::checkMember($member, 'MANAGE_FOXY_PRODUCTS');
319
    }
320
321
    /**
322
     * @param $member
323
     * @return bool|int|void|null
324
     */
325
    public function canEdit($member)
326
    {
327
        if (!$member) {
328
            $member = Security::getCurrentUser();
329
        }
330
331
        return Permission::checkMember($member, 'MANAGE_FOXY_PRODUCTS');
332
    }
333
334
    /**
335
     * @param $member
336
     * @return bool|int|void
337
     */
338
    public function canDelete($member)
339
    {
340
        if (!$member) {
341
            $member = Security::getCurrentUser();
342
        }
343
344
        return Permission::checkMember($member, 'MANAGE_FOXY_PRODUCTS');
345
    }
346
347
    /**
348
     * @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...
349
     * @return bool|int
350
     */
351
    public function canUnpublish($member = null)
352
    {
353
        if (!$member) {
0 ignored issues
show
introduced by
$member is of type null, thus it always evaluated to false.
Loading history...
354
            $member = Security::getCurrentUser();
355
        }
356
357
        return Permission::checkMember($member, 'MANAGE_FOXY_PRODUCTS');
358
    }
359
360
    /**
361
     * @param $member
362
     * @return bool|int
363
     */
364
    public function canArchive($member = null)
365
    {
366
        if (!$member) {
367
            $member = Security::getCurrentUser();
368
        }
369
370
        return Permission::checkMember($member, 'MANAGE_FOXY_PRODUCTS');
371
    }
372
373
    /**
374
     *
375
     */
376
    public function onBeforeWrite()
377
    {
378
        // trim spaces and replace duplicate spaces
379
        $trimmed = trim($this->owner->Code);
380
        $this->owner->Code = preg_replace('/\s+/', ' ', $trimmed);
381
    }
382
}
383