Completed
Pull Request — master (#374)
by Jason
07:43 queued 04:32
created

ProductPage::populateDefaults()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 7
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 2.0625
1
<?php
2
3
namespace Dynamic\FoxyStripe\Page;
4
5
use Bummzack\SortableFile\Forms\SortableUploadField;
6
use Dynamic\FoxyStripe\Model\FoxyCart;
7
use Dynamic\FoxyStripe\Model\FoxyStripeSetting;
8
use Dynamic\FoxyStripe\Model\OptionItem;
9
use Dynamic\FoxyStripe\Model\OrderDetail;
10
use Dynamic\FoxyStripe\Model\ProductCategory;
11
use Dynamic\FoxyStripe\Model\ProductImage;
12
use SilverStripe\AssetAdmin\Forms\UploadField;
13
use SilverStripe\Assets\Image;
14
use SilverStripe\CMS\Controllers\ContentController;
15
use SilverStripe\Control\Controller;
16
use SilverStripe\Forms\CheckboxField;
17
use SilverStripe\Forms\CurrencyField;
18
use SilverStripe\Forms\DropdownField;
19
use SilverStripe\Forms\FieldList;
20
use SilverStripe\Forms\GridField\GridField;
21
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
22
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
23
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
24
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
25
use SilverStripe\Forms\HeaderField;
26
use SilverStripe\Forms\LiteralField;
27
use SilverStripe\Forms\NumericField;
28
use SilverStripe\Forms\RequiredFields;
29
use SilverStripe\Forms\TextField;
30
use SilverStripe\Security\Member;
31
use SilverStripe\Security\Permission;
32
use SilverStripe\Security\PermissionProvider;
33
use SilverStripe\View\Requirements;
34
use Symbiote\GridFieldExtensions\GridFieldOrderableRows;
35
36
/**
37
 * Class ProductPage
38
 * @package Dynamic\FoxyStripe\Page
39
 *
40
 * @property \SilverStripe\ORM\FieldType\DBCurrency $Price
41
 * @property \SilverStripe\ORM\FieldType\DBDecimal $Weight
42
 * @property \SilverStripe\ORM\FieldType\DBVarchar $Code
43
 * @property \SilverStripe\ORM\FieldType\DBVarchar $ReceiptTitle
44
 * @property \SilverStripe\ORM\FieldType\DBBoolean $Featured
45
 * @property \SilverStripe\ORM\FieldType\DBBoolean $Available
46
 *
47
 * @property int $CategoryID
48
 * @method ProductCategory Category()
49
 *
50
 * @method \SilverStripe\ORM\HasManyList ProductOptions()
51
 * @method \SilverStripe\ORM\HasManyList OrderDetails()
52
 *
53
 * @method \SilverStripe\ORM\ManyManyList Images()
54
 *
55
 * @method \SilverStripe\ORM\ManyManyList ProductHolders()
56
 */
57
class ProductPage extends \Page implements PermissionProvider
58
{
59
    /**
60
     * @var string
61
     */
62
    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...
63
64
    /**
65
     * @var bool
66
     */
67
    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...
68
69
    /**
70
     * @var array
71
     */
72
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
73
        'Price' => 'Currency',
74
        'Weight' => 'Decimal',
75
        'Code' => 'Varchar(100)',
76
        'ReceiptTitle' => 'HTMLVarchar(255)',
77
        'Available' => 'Boolean',
78
    ];
79
80
    /**
81
     * @var array
82
     */
83
    private static $has_one = [
0 ignored issues
show
introduced by
The private property $has_one is not used, and could be removed.
Loading history...
84
        'Category' => ProductCategory::class,
85
    ];
86
87
    /**
88
     * @var array
89
     */
90
    private static $has_many = [
0 ignored issues
show
introduced by
The private property $has_many is not used, and could be removed.
Loading history...
91
        'ProductOptions' => OptionItem::class,
92
        'OrderDetails' => OrderDetail::class,
93
    ];
94
95
    /**
96
     * @var array
97
     */
98
    private static $many_many = [
0 ignored issues
show
introduced by
The private property $many_many is not used, and could be removed.
Loading history...
99
        'Images' => Image::class,
100
    ];
101
102
    /**
103
     * @var array
104
     */
105
    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...
106
        'Images' => [
107
            'SortOrder' => 'Int',
108
        ],
109
    ];
110
111
    /**
112
     * @var array
113
     */
114
    private static $owns = [
0 ignored issues
show
introduced by
The private property $owns is not used, and could be removed.
Loading history...
115
        'Images',
116
    ];
117
118
    /**
119
     * @var array
120
     */
121
    private static $belongs_many_many = [
0 ignored issues
show
introduced by
The private property $belongs_many_many is not used, and could be removed.
Loading history...
122
        'ProductHolders' => ProductHolder::class,
123
    ];
124
125
    /**
126
     * @var string
127
     */
128
    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...
129
130
    /**
131
     * @var string
132
     */
133
    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...
134
135
    /**
136
     * @var string
137
     */
138
    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...
139
140
    /**
141
     * @var array
142
     */
143
    private static $indexes = [
0 ignored issues
show
introduced by
The private property $indexes is not used, and could be removed.
Loading history...
144
        'Code' => [
145
            'type' => 'unique',
146
            'columns' => ['Code'],
147
        ],
148
    ];
149
150
    /**
151
     * @var array
152
     */
153
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
154
        'Image.CMSThumbnail',
155
        'Title',
156
        'Code',
157
        'Price.Nice',
158
        'Category.Title',
159
    ];
160
161
    /**
162
     * @var array
163
     */
164
    private static $searchable_fields = [
0 ignored issues
show
introduced by
The private property $searchable_fields is not used, and could be removed.
Loading history...
165
        'Title',
166
        'Code',
167
        'Available',
168
        'Category.ID',
169
    ];
170
171
    /**
172
     * @var string
173
     */
174
    private static $table_name = 'ProductPage';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
175
176
    /**
177
     * @var array
178
     */
179
    private static $defaults = [
0 ignored issues
show
introduced by
The private property $defaults is not used, and could be removed.
Loading history...
180
        'ShowInMenus' => false,
181
        'Available' => true,
182
        'Weight' => '0.0',
183
    ];
184
185
    /**
186
     * @return \SilverStripe\ORM\DataObject|void
187
     */
188 9
    public function populateDefaults()
189
    {
190 9
        if ($cat = ProductCategory::get()->filter('Code', 'DEFAULT')->first()) {
191
            $this->CategoryID = $cat->ID;
192
        }
193
194 9
        parent::populateDefaults();
195
    }
196
197
    /**
198
     * Construct a new ProductPage.
199
     *
200
     * @param array|null $record Used internally for rehydrating an object from database content.
201
     *                           Bypasses setters on this class, and hence should not be used
202
     *                           for populating data on new records.
203
     * @param boolean $isSingleton This this to true if this is a singleton() object, a stub for calling methods.
204
     *                             Singletons don't have their defaults set.
205
     * @param array $queryParams List of DataQuery params necessary to lazy load, or load related objects.
206
     */
207 14
    public function __construct($record = null, $isSingleton = false, $queryParams = [])
208
    {
209 14
        parent::__construct($record, $isSingleton, $queryParams);
210
211 14
        if (Controller::curr() instanceof ContentController) {
212
            Requirements::javascript('dynamic/foxystripe: javascript/quantity.js');
213
            Requirements::css('dynamic/foxystripe: client/dist/css/quantityfield.css');
214
        }
215
    }
216
217
    /**
218
     * @param bool $includerelations
219
     *
220
     * @return array
221
     */
222
    public function fieldLabels($includerelations = true)
223
    {
224
        $labels = parent::fieldLabels();
225
226
        $labels['Title'] = _t('ProductPage.TitleLabel', 'Product Name');
227
        $labels['Code'] = _t('ProductPage.CodeLabel', 'Code');
228
        $labels['Price.Nice'] = _t('ProductPage.PriceLabel', 'Price');
229
        $labels['Available.Nice'] = _t('ProductPage.AvailableLabel', 'Available');
230
        $labels['Category.ID'] = _t('ProductPage.IDLabel', 'Category');
231
        $labels['Category.Title'] = _t('ProductPage.CategoryTitleLabel', 'Category');
232
        $labels['Image.CMSThumbnail'] = _t('ProductPage.ImageLabel', 'Image');
233
234
        return $labels;
235
    }
236
237
    /**
238
     * @return \SilverStripe\Forms\FieldList
239
     */
240
    public function getCMSFields()
241
    {
242
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
243
            $fields->addFieldsToTab(
244
                'Root.Main',
245
                [
246
                    TextField::create('Code')
247
                        ->setTitle(_t('ProductPage.Code', 'Product Code'))
248
                        ->setDescription(_t(
249
                            'ProductPage.CodeDescription',
250
                            'Required, must be unique. Product identifier used by FoxyCart in transactions'
251
                        )),
252
                    CurrencyField::create('Price')
253
                        ->setTitle(_t('ProductPage.Price', 'Price'))
254
                        ->setDescription(_t(
255
                            'ProductPage.PriceDescription',
256
                            'Base price for this product. Can be modified using Product Options'
257
                        )),
258
                    NumericField::create('Weight')
259
                        ->setTitle(_t('ProductPage.Weight', 'Weight'))
260
                        ->setDescription(_t(
261
                            'ProductPage.WeightDescription',
262
                            'Base weight for this product in lbs. Can be modified using Product Options'
263
                        ))
264
                        ->setScale(2),
265
                    DropdownField::create(
266
                        'CategoryID',
267
                        _t('ProductPage.Category', 'Product Category'),
268
                        ProductCategory::get()->map()->toArray()
269
                    )
270
                        ->setDescription(_t(
271
                            'ProductPage.CategoryDescription',
272
                            'Required, must also exist in 
273
                    <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">
274
                        FoxyCart Categories
275
                    </a>.
276
                    Used to set category specific options like shipping and taxes. Managed in
277
                        <a href="admin/foxystripe">
278
                            FoxyStripe > Categories
279
                        </a>'
280
                        )),
281
                ],
282
                'Content'
283
            );
284
285
            // Product Options field
286
            $config = GridFieldConfig_RelationEditor::create();
287
            $config->addComponent(new GridFieldOrderableRows('SortOrder'));
288
            $products = $this->ProductOptions()->sort('SortOrder');
289
            $config->removeComponentsByType(GridFieldAddExistingAutocompleter::class);
290
            $prodOptField = GridField::create(
291
                'ProductOptions',
292
                _t('ProductPage.ProductOptions', 'Options'),
293
                $products,
294
                $config
295
            );
296
297
            // Details tab
298
            $fields->addFieldsToTab('Root.Details', [
299
                CheckboxField::create('Available')
300
                    ->setTitle(_t('ProductPage.Available', 'Available for purchase'))
301
                    ->setDescription(_t(
302
                        'ProductPage.AvailableDescription',
303
                        'If unchecked, will remove "Add to Cart" form and instead display "Currently unavailable"'
304
                    )),
305
                TextField::create('ReceiptTitle')
306
                    ->setTitle(_t('ProductPage.ReceiptTitle', 'Product Title for Receipt'))
307
                    ->setDescription(_t(
308
                        'ProductPage.ReceiptTitleDescription',
309
                        'Optional'
310
                    )),
311
            ]);
312
313
            // Options Tab
314
            $fields->addFieldsToTab('Root.Options', [
315
                $prodOptField
316
                    ->setDescription(_t(
317
                        'Page.OptionsDescrip',
318
                        '<p>Product Options allow products to be customized by attributes such as size or color.
319
                    Options can also modify the product\'s price, weight or code.<br></p>'
320
                    )),
321
            ]);
322
323
            // Images tab
324
            $images = SortableUploadField::create('Images')
325
                ->setSortColumn('SortOrder')
326
                ->setIsMultiUpload(true)
327
                ->setAllowedFileCategories('image')
328
                ->setFolderName('Uploads/Products/Images');
329
330
            $fields->addFieldsToTab('Root.Images', [
331
                $images,
332
            ]);
333
334
            if (FoxyCart::store_name_warning() !== null) {
335
                $fields->addFieldToTab('Root.Main', LiteralField::create('StoreSubDomainHeaderWarning', _t(
336
                    'ProductPage.StoreSubDomainHeaderWarning',
337
                    '<p class="message error">Store sub-domain must be entered in the 
338
                        <a href="/admin/settings/">site settings</a></p>'
339
                )), 'Title');
340
            }
341
        });
342
343
        $fields = parent::getCMSFields();
344
345
        $fields->dataFieldByName('Content')->setTitle('Description');
346
347
        return $fields;
348
    }
349
350
    /**
351
     * @return RequiredFields
352
     */
353
    public function getCMSValidator()
354
    {
355
        return new RequiredFields(['CategoryID', 'Price', 'Code']);
356
    }
357
358
    /**
359
     * @return \SilverStripe\ORM\ValidationResult
360
     */
361 5
    public function validate()
362
    {
363 5
        $result = parent::validate();
364
365 5
        if (ProductPage::get()->filter('Code', $this->Code)->exclude('ID', $this->ID)->first()) {
366
            $result->addError('Code must be unique for each product.');
367
        }
368
369
        /*if($this->ID>0){
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
370
            if ($this->Price <= 0) {
371
                $result->addError('Price must be a positive value');
372
            }
373
            if($this->Weight <= 0){
374
                $result->error('Must set a positive weight value');
375
            }
376
            if($this->Code == ''){
377
                $result->error('Must set a product code');
378
            }
379
        }*/
380
381 5
        return $result;
382
    }
383
384
    /**
385
     * @return \SilverStripe\ORM\ManyManyList
386
     */
387
    public function getSortedImages()
388
    {
389
        return $this->Images()->Sort('SortOrder');
390
    }
391
392
    /**
393
     * @return \SilverStripe\ORM\ManyManyList
394
     */
395
    public function SortedImages()
396
    {
397
        return $this->getSortedImages();
398
    }
399
400
    /**
401
     * @return Image|bool
402
     */
403
    public function getImage()
404
    {
405
        if ($this->getSortedImages()->count() > 0) {
406
            return $this->getSortedImages()->first();
407
        }
408
        return false;
409
    }
410
411
    /**
412
     * @return Image|bool
413
     */
414
    public function Image()
415
    {
416
        return $this->getImage();
417
    }
418
419
    /**
420
     * @throws \Exception
421
     */
422 13
    public function onBeforeWrite()
423
    {
424 13
        parent::onBeforeWrite();
425 13
        if (!$this->CategoryID) {
426
            $default = ProductCategory::get()->filter(['Code' => 'DEFAULT'])->first();
427
            $this->CategoryID = $default->ID;
428
        }
429
430
        //update many_many lists when multi-group is on
431 13
        if (FoxyStripeSetting::current_foxystripe_setting()->MultiGroup) {
432
            $holders = $this->ProductHolders();
433
            $product = self::get()->byID($this->ID);
434
            if (isset($product->ParentID)) {
435
                $origParent = $product->ParentID;
436
            } else {
437
                $origParent = null;
438
            }
439
            $currentParent = $this->ParentID;
440
            if ($origParent != $currentParent) {
441
                if ($holders->find('ID', $origParent)) {
442
                    $holders->removeByID($origParent);
443
                }
444
            }
445
            $holders->add($currentParent);
446
        }
447
448 13
        $this->Title = trim($this->Title);
449 13
        $this->Code = trim($this->Code);
0 ignored issues
show
Documentation Bug introduced by
It seems like trim($this->Code) of type string is incompatible with the declared type SilverStripe\ORM\FieldType\DBVarchar of property $Code.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
450 13
        $this->ReceiptTitle = trim($this->ReceiptTitle);
0 ignored issues
show
Documentation Bug introduced by
It seems like trim($this->ReceiptTitle) of type string is incompatible with the declared type SilverStripe\ORM\FieldType\DBVarchar of property $ReceiptTitle.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
451
    }
452
453 13
    public function onAfterWrite()
454
    {
455 13
        parent::onAfterWrite();
456
    }
457
458 2
    public function onBeforeDelete()
459
    {
460 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...
461 2
            if ($this->ProductOptions()) {
462 2
                $options = $this->getComponents('ProductOptions');
463 2
                foreach ($options as $option) {
464
                    $option->delete();
465
                }
466
            }
467
        }
468 2
        parent::onBeforeDelete();
469
    }
470
471
    /**
472
     * @param null $productCode
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $productCode is correct as it would always require null to be passed?
Loading history...
473
     * @param null $optionName
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $optionName is correct as it would always require null to be passed?
Loading history...
474
     * @param null $optionValue
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $optionValue is correct as it would always require null to be passed?
Loading history...
475
     * @param string $method
476
     * @param bool $output
477
     * @param bool $urlEncode
478
     *
479
     * @return null|string
480
     */
481
    public static function getGeneratedValue(
482
        $productCode = null,
483
        $optionName = null,
484
        $optionValue = null,
485
        $method = 'name',
486
        $output = false,
487
        $urlEncode = false
488
    ) {
489
        $optionName = ($optionName !== null) ? preg_replace('/\s/', '_', $optionName) : $optionName;
0 ignored issues
show
introduced by
The condition $optionName !== null is always false.
Loading history...
490
491
        return (FoxyStripeSetting::current_foxystripe_setting()->CartValidation)
492
            ? \FoxyCart_Helper::fc_hash_value($productCode, $optionName, $optionValue, $method, $output, $urlEncode) :
493
            $optionValue;
494
    }
495
496
    /**
497
     * @param Member $member
498
     *
499
     * @return bool
500
     */
501
    public function canEdit($member = null)
502
    {
503
        return Permission::check('Product_CANCRUD', 'any', $member);
504
    }
505
506
    public function canDelete($member = null)
507
    {
508
        return Permission::check('Product_CANCRUD', 'any', $member);
509
    }
510
511
    public function canCreate($member = null, $context = [])
512
    {
513
        return Permission::check('Product_CANCRUD', 'any', $member);
514
    }
515
516
    public function canPublish($member = null)
517
    {
518
        return Permission::check('Product_CANCRUD', 'any', $member);
519
    }
520
521
    public function providePermissions()
522
    {
523
        return [
524
            'Product_CANCRUD' => 'Allow user to manage Products and related objects',
525
        ];
526
    }
527
}
528