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

ProductPage::getCMSFields()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 122
Code Lines 88

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 122
ccs 0
cts 81
cp 0
rs 8.1935
cc 4
eloc 88
nc 8
nop 0
crap 20

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\Page;
4
5
use Dynamic\FoxyStripe\Model\FoxyCart;
6
use Dynamic\FoxyStripe\Model\OptionItem;
7
use Dynamic\FoxyStripe\Model\OrderDetail;
8
use Dynamic\FoxyStripe\Model\ProductCategory;
9
use Dynamic\FoxyStripe\Model\ProductImage;
10
use SilverStripe\AssetAdmin\Forms\UploadField;
11
use SilverStripe\Assets\Image;
12
use SilverStripe\Forms\CheckboxField;
13
use SilverStripe\Forms\CurrencyField;
14
use SilverStripe\Forms\DropdownField;
15
use SilverStripe\Forms\GridField\GridField;
16
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
17
use SilverStripe\Forms\HeaderField;
18
use SilverStripe\Forms\LiteralField;
19
use SilverStripe\Forms\NumericField;
20
use SilverStripe\Forms\RequiredFields;
21
use SilverStripe\Forms\TextField;
22
use SilverStripe\Security\Permission;
23
use SilverStripe\Security\PermissionProvider;
24
use SilverStripe\SiteConfig\SiteConfig;
25
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;
26
27
class ProductPage extends \Page implements PermissionProvider
28
{
29
    /**
30
     * @var string
31
     */
32
    //private static $allowed_children = [];
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
33
34
    /**
35
     * @var string
36
     */
37
    private static $default_parent = ProductHolder::class;
0 ignored issues
show
introduced by
The private property $default_parent is not used, and could be removed.
Loading history...
38
39
    /**
40
     * @var bool
41
     */
42
    private static $can_be_root = false;
0 ignored issues
show
introduced by
The private property $can_be_root is not used, and could be removed.
Loading history...
43
44
    /**
45
     * @var array
46
     */
47
    private static $db = array(
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
48
        'Price' => 'Currency',
49
        'Weight' => 'Decimal',
50
        'Code' => 'Varchar(100)',
51
        'ReceiptTitle' => 'HTMLVarchar(255)',
52
        'Featured' => 'Boolean',
53
        'Available' => 'Boolean',
54
    );
55
56
    /**
57
     * @var array
58
     */
59
    private static $has_one = array(
0 ignored issues
show
introduced by
The private property $has_one is not used, and could be removed.
Loading history...
60
        'PreviewImage' => Image::class,
61
        'Category' => ProductCategory::class,
62
    );
63
64
    /**
65
     * @var array
66
     */
67
    private static $has_many = array(
0 ignored issues
show
introduced by
The private property $has_many is not used, and could be removed.
Loading history...
68
        'ProductImages' => ProductImage::class,
69
        'ProductOptions' => OptionItem::class,
70
        'OrderDetails' => OrderDetail::class,
71
    );
72
73
    /**
74
     * @var array
75
     */
76
    private static $belongs_many_many = array(
0 ignored issues
show
introduced by
The private property $belongs_many_many is not used, and could be removed.
Loading history...
77
        'ProductHolders' => ProductHolder::class,
78
    );
79
80
    /**
81
     * @var string
82
     */
83
    private static $singular_name = 'Product';
0 ignored issues
show
introduced by
The private property $singular_name is not used, and could be removed.
Loading history...
84
85
    /**
86
     * @var string
87
     */
88
    private static $plural_name = 'Products';
0 ignored issues
show
introduced by
The private property $plural_name is not used, and could be removed.
Loading history...
89
90
    /**
91
     * @var string
92
     */
93
    private static $description = 'A product that can be added to the shopping cart';
0 ignored issues
show
introduced by
The private property $description is not used, and could be removed.
Loading history...
94
95
    /**
96
     * @var array
97
     */
98
    private static $indexes = array(
0 ignored issues
show
introduced by
The private property $indexes is not used, and could be removed.
Loading history...
99
        'Code' => true, // make unique
100
    );
101
102
    /**
103
     * @var array
104
     */
105
    private static $defaults = array(
0 ignored issues
show
introduced by
The private property $defaults is not used, and could be removed.
Loading history...
106
        'ShowInMenus' => false,
107
        'Available' => true,
108
        'Weight' => '1.0',
109
    );
110
111
    /**
112
     * @var array
113
     */
114
    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...
115
        'Title',
116
        'Code',
117
        'Price.Nice',
118
        'Category.Title',
119
    );
120
121
    /**
122
     * @var array
123
     */
124
    private static $searchable_fields = array(
0 ignored issues
show
introduced by
The private property $searchable_fields is not used, and could be removed.
Loading history...
125
        'Title',
126
        'Code',
127
        'Featured',
128
        'Available',
129
        'Category.ID',
130
    );
131
132
    /**
133
     * @var string
134
     */
135
    private static $table_name = 'FS_ProductPage';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
136
137
    /**
138
     * @param bool $includerelations
139
     *
140
     * @return array
141
     */
142
    public function fieldLabels($includerelations = true)
143
    {
144
        $labels = parent::fieldLabels();
145
146
        $labels['Title'] = _t('ProductPage.TitleLabel', 'Name');
147
        $labels['Code'] = _t('ProductPage.CodeLabel', 'Code');
148
        $labels['Price.Nice'] = _t('ProductPage.PriceLabel', 'Price');
149
        $labels['Featured.Nice'] = _t('ProductPage.NiceLabel', 'Featured');
150
        $labels['Available.Nice'] = _t('ProductPage.AvailableLabel', 'Available');
151
        $labels['Category.ID'] = _t('ProductPage.IDLabel', 'Category');
152
        $labels['Category.Title'] = _t('ProductPage.CategoryTitleLabel', 'Category');
153
154
        return $labels;
155
    }
156
157
    /**
158
     * @return \SilverStripe\Forms\FieldList
159
     */
160
    public function getCMSFields()
161
    {
162
        $fields = parent::getCMSFields();
163
164
        // allow extensions of ProductPage to override the PreviewImage field description
165
        $previewDescription = ($this->stat('customPreviewDescription')) ? $this->stat('customPreviewDescription') : _t('ProductPage.PreviewImageDescription',
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\View\ViewableData::stat() has been deprecated: 5.0 Use ->config()->get() instead ( Ignorable by Annotation )

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

165
        $previewDescription = ($this->stat('customPreviewDescription')) ? /** @scrutinizer ignore-deprecated */ $this->stat('customPreviewDescription') : _t('ProductPage.PreviewImageDescription',

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
166
            'Image used throughout site to represent this product');
167
168
        // Cateogry Dropdown field w/ add new
169
        $source = function () {
170
            return ProductCategory::get()->map()->toArray();
171
        };
172
        $catField = DropdownField::create('CategoryID', _t('ProductPage.Category', 'FoxyCart Category'), $source())
0 ignored issues
show
Bug introduced by
'CategoryID' 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

172
        $catField = DropdownField::create(/** @scrutinizer ignore-type */ 'CategoryID', _t('ProductPage.Category', 'FoxyCart Category'), $source())
Loading history...
173
            ->setEmptyString('')
174
            ->setDescription(_t(
175
                'ProductPage.CategoryDescription',
176
                'Required, must also exist in 
177
                    <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">
178
                        FoxyCart Categories
179
                    </a>.
180
                    Used to set category specific options like shipping and taxes. Managed in
181
                        <a href="admin/settings">
182
                            Settings > FoxyStripe > Categories
183
                        </a>'
184
            ));
185
        if (class_exists('QuickAddNewExtension')) {
186
            $catField->useAddNew('ProductCategory', $source);
187
        }
188
189
        // Product Images gridfield
190
        $config = GridFieldConfig_RelationEditor::create();
191
        $config->addComponent(new GridFieldOrderableRows('SortOrder'));
192
        $prodImagesField = GridField::create(
193
            'ProductImages',
194
            _t('ProductPage.ProductImages', 'Images'),
195
            $this->ProductImages(),
0 ignored issues
show
Bug introduced by
The method ProductImages() does not exist on Dynamic\FoxyStripe\Page\ProductPage. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

195
            $this->/** @scrutinizer ignore-call */ 
196
                   ProductImages(),
Loading history...
196
            $config
197
        );
198
199
        // Product Options field
200
        $config = GridFieldConfig_RelationEditor::create();
201
        $config->addComponent(new GridFieldOrderableRows('SortOrder'));
202
        $products = $this->ProductOptions()->sort('SortOrder');
0 ignored issues
show
Bug introduced by
The method ProductOptions() does not exist on Dynamic\FoxyStripe\Page\ProductPage. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

202
        $products = $this->/** @scrutinizer ignore-call */ ProductOptions()->sort('SortOrder');
Loading history...
203
        $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
204
        $prodOptField = GridField::create(
205
            'ProductOptions',
206
            _t('ProductPage.ProductOptions', 'Options'),
207
            $products,
208
            $config
209
        );
210
211
        // Details tab
212
        $fields->addFieldsToTab('Root.Details', array(
213
            HeaderField::create('DetailHD', 'Product Details', 2),
0 ignored issues
show
Bug introduced by
2 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

213
            HeaderField::create('DetailHD', 'Product Details', /** @scrutinizer ignore-type */ 2),
Loading history...
214
            CheckboxField::create('Available')
215
                ->setTitle(_t('ProductPage.Available', 'Available for purchase'))
216
                ->setDescription(_t(
217
                    'ProductPage.AvailableDescription',
218
                    'If unchecked, will remove "Add to Cart" form and instead display "Currently unavailable"'
219
                )),
220
            TextField::create('Code')
221
                ->setTitle(_t('ProductPage.Code', 'Product Code'))
222
                ->setDescription(_t(
223
                    'ProductPage.CodeDescription',
224
                    'Required, must be unique. Product identifier used by FoxyCart in transactions'
225
                )),
226
            $catField,
227
            CurrencyField::create('Price')
228
                ->setTitle(_t('ProductPage.Price', 'Price'))
229
                ->setDescription(_t(
230
                    'ProductPage.PriceDescription',
231
                    'Base price for this product. Can be modified using Product Options'
232
                )),
233
            NumericField::create('Weight')
234
                ->setTitle(_t('ProductPage.Weight', 'Weight'))
235
                ->setDescription(_t(
236
                    'ProductPage.WeightDescription',
237
                    'Base weight for this product in lbs. Can be modified using Product Options'
238
                )),
239
            CheckboxField::create('Featured')
240
                ->setTitle(_t('ProductPage.Featured', 'Featured Product')),
241
            TextField::create('ReceiptTitle')
242
                ->setTitle(_t('ProductPage.ReceiptTitle', 'Product Title for Receipt'))
243
                ->setDescription(_t(
244
                    'ProductPage.ReceiptTitleDescription', 'Optional'
245
                )),
246
        ));
247
248
        // Images tab
249
        $fields->addFieldsToTab('Root.Images', array(
250
            HeaderField::create('MainImageHD', _t('ProductPage.MainImageHD', 'Product Image'), 2),
251
            UploadField::create('PreviewImage', '')
252
                ->setDescription($previewDescription)
253
                ->setFolderName('Uploads/Products')
254
                ->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png')),
255
            HeaderField::create('ProductImagesHD', _t('ProductPage.ProductImagesHD', 'Product Image Gallery'), 2),
256
            $prodImagesField
257
                ->setDescription(_t(
258
                    'ProductPage.ProductImagesDescription',
259
                    'Additional Product Images, shown in gallery on Product page'
260
                )),
261
        ));
262
263
        // Options Tab
264
        $fields->addFieldsToTab('Root.Options', array(
265
            HeaderField::create('OptionsHD', _t('ProductPage.OptionsHD', 'Product Options'), 2),
266
            LiteralField::create('OptionsDescrip', _t(
267
                'Page.OptionsDescrip',
268
                '<p>Product Options allow products to be customized by attributes such as size or color.
269
                    Options can also modify the product\'s price, weight or code.</p>'
270
            )),
271
            $prodOptField,
272
        ));
273
274
        if (FoxyCart::store_name_warning() !== null) {
275
            $fields->addFieldToTab('Root.Main', LiteralField::create('StoreSubDomainHeaderWarning', _t(
276
                'ProductPage.StoreSubDomainHeaderWarning',
277
                '<p class="message error">Store sub-domain must be entered in the <a href="/admin/settings/">site settings</a></p>'
278
            )), 'Title');
279
        }
280
281
        return $fields;
282
    }
283
284 49
    public function onBeforeWrite()
285
    {
286 49
        parent::onBeforeWrite();
287 49
        if (!$this->CategoryID) {
288
            $default = ProductCategory::get()->filter(array('Code' => 'DEFAULT'))->first();
289
            $this->CategoryID = $default->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CategoryID does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
290
        }
291
292
        //update many_many lists when multi-group is on
293 49
        if (SiteConfig::current_site_config()->MultiGroup) {
294
            $holders = $this->ProductHolders();
0 ignored issues
show
Bug introduced by
The method ProductHolders() does not exist on Dynamic\FoxyStripe\Page\ProductPage. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

294
            /** @scrutinizer ignore-call */ 
295
            $holders = $this->ProductHolders();
Loading history...
295
            $product = self::get()->byID($this->ID);
296
            if (isset($product->ParentID)) {
297
                $origParent = $product->ParentID;
298
            } else {
299
                $origParent = null;
300
            }
301
            $currentParent = $this->ParentID;
302
            if ($origParent != $currentParent) {
303
                if ($holders->find('ID', $origParent)) {
304
                    $holders->removeByID($origParent);
305
                }
306
            }
307
            $holders->add($currentParent);
308
        }
309
310 49
        $title = ltrim($this->Title);
311 49
        $title = rtrim($title);
312 49
        $this->Title = $title;
313
    }
314
315 49
    public function onAfterWrite()
316
    {
317 49
        parent::onAfterWrite();
318
    }
319
320 2
    public function onBeforeDelete()
321
    {
322 2
        if ($this->Status != 'Published') {
0 ignored issues
show
Bug Best Practice introduced by
The property Status does not exist on Dynamic\FoxyStripe\Page\ProductPage. Since you implemented __get, consider adding a @property annotation.
Loading history...
323 2
            if ($this->ProductOptions()) {
324 2
                $options = $this->getComponents('ProductOptions');
325 2
                foreach ($options as $option) {
326
                    $option->delete();
327
                }
328
            }
329 2
            if ($this->ProductImages()) {
330
                //delete product image dataobjects, not the images themselves.
331 2
                $images = $this->getComponents('ProductImages');
332 2
                foreach ($images as $image) {
333
                    $image->delete();
334
                }
335
            }
336
        }
337 2
        parent::onBeforeDelete();
338
    }
339
340 5
    public function validate()
341
    {
342 5
        $result = parent::validate();
343
344
        /*if($this->ID>0){
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...
345
            if($this->Price <= 0) {
346
                $result->error('Must set a positive price value');
347
            }
348
            if($this->Weight <= 0){
349
                $result->error('Must set a positive weight value');
350
            }
351
            if($this->Code == ''){
352
                $result->error('Must set a product code');
353
            }
354
        }*/
355
356 5
        return $result;
357
    }
358
359
    public function getCMSValidator()
360
    {
361
        return new RequiredFields(array('CategoryID', 'Price', 'Weight', 'Code'));
362
    }
363
364
    public static function getGeneratedValue(
365
        $productCode = null,
366
        $optionName = null,
367
        $optionValue = null,
368
        $method = 'name',
369
        $output = false,
370
        $urlEncode = false
371
    ) {
372
        $optionName = ($optionName !== null) ? preg_replace('/\s/', '_', $optionName) : $optionName;
373
374
        return (SiteConfig::current_site_config()->CartValidation)
375
            ? \FoxyCart_Helper::fc_hash_value($productCode, $optionName, $optionValue, $method, $output, $urlEncode) :
376
            $optionValue;
377
    }
378
379
    // get FoxyCart Store Name for JS call
380
    public function getCartScript()
381
    {
382
        return '<script src="https://cdn.foxycart.com/'.FoxyCart::getFoxyCartStoreName().'/loader.js" async defer></script>';
383
    }
384
385
    /**
386
     * @param Member $member
0 ignored issues
show
Bug introduced by
The type Dynamic\FoxyStripe\Page\Member was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
387
     *
388
     * @return bool
389
     */
390
    public function canEdit($member = null)
391
    {
392
        return Permission::check('Product_CANCRUD', 'any', $member);
393
    }
394
395
    public function canDelete($member = null)
396
    {
397
        return Permission::check('Product_CANCRUD', 'any', $member);
398
    }
399
400
    public function canCreate($member = null, $context = [])
401
    {
402
        return Permission::check('Product_CANCRUD', 'any', $member);
403
    }
404
405 2
    public function canPublish($member = null)
406
    {
407 2
        return Permission::check('Product_CANCRUD', 'any', $member);
408
    }
409
410
    public function providePermissions()
411
    {
412
        return array(
413
            'Product_CANCRUD' => 'Allow user to manage Products and related objects',
414
        );
415
    }
416
}
417