Passed
Pull Request — master (#99)
by Nic
03:01
created

Variation::onBeforeWrite()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 15
c 0
b 0
f 0
nc 8
nop 0
dl 0
loc 23
rs 9.4555
1
<?php
2
3
namespace Dynamic\Foxy\Model;
4
5
use Bummzack\SortableFile\Forms\SortableUploadField;
6
use SilverStripe\Assets\File;
7
use SilverStripe\Forms\CheckboxField;
8
use SilverStripe\Forms\CurrencyField;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Forms\FieldGroup;
11
use SilverStripe\Forms\FieldList;
12
use SilverStripe\Forms\NumericField;
13
use SilverStripe\Forms\ReadonlyField;
14
use SilverStripe\Forms\TextField;
15
use SilverStripe\ORM\DataObject;
16
use SilverStripe\ORM\ValidationResult;
17
18
/**
19
 * Class Variation
20
 * @package Dynamic\Foxy\Model
21
 */
22
class Variation extends DataObject
23
{
24
    /**
25
     * @var string
26
     */
27
    private static $table_name = 'Variation';
28
29
    /**
30
     * @var string
31
     */
32
    private static $singular_name = 'Variation';
33
34
    /**
35
     * @var string
36
     */
37
    private static $plural_name = 'Variations';
38
39
    /**
40
     * @var string[]
41
     */
42
    private static $db = [
43
        'Title' => 'Varchar(255)',
44
        'UseProductContent' => 'Boolean',
45
        'Content' => 'HTMLText',
46
        'WeightModifier' => 'Decimal(9,3)',
47
        'CodeModifier' => 'Text',
48
        'PriceModifier' => 'Currency',
49
        'WeightModifierAction' => "Enum('Add,Subtract,Set', null)",
50
        'CodeModifierAction' => "Enum('Add,Subtract,Set', null)",
51
        'PriceModifierAction' => "Enum('Add,Subtract,Set', null)",
52
        'Available' => 'Boolean',
53
        'Type' => 'Int',
54
        'OptionModifierKey' => 'Varchar(255)',
55
        'SortOrder' => 'Int',
56
    ];
57
58
    /**
59
     * @var string[]
60
     */
61
    private static $has_one = [
62
        'VariationType' => VariationType::class,
63
    ];
64
65
    /**
66
     * @var array
67
     */
68
    private static $many_many = [
69
        'Images' => File::class,
70
    ];
71
72
    /**
73
     * @var \string[][]
74
     */
75
    private static $many_many_extraFields = [
76
        'Images' => [
77
            'SortOrder' => 'Int',
78
        ],
79
    ];
80
81
    /**
82
     * @var string[]
83
     */
84
    private static $owns = [
85
        'Images',
86
    ];
87
88
    /**
89
     * The relation name was established before requests for videos.
90
     * The relation has subsequently been updated from Image::class to File::class
91
     * to allow for additional file types such as mp4
92
     *
93
     * @var array
94
     */
95
    private static $allowed_images_extensions = [
96
        'gif',
97
        'jpeg',
98
        'jpg',
99
        'png',
100
        'bmp',
101
        'ico',
102
        'mp4',
103
    ];
104
105
    /**
106
     * @return FieldList
107
     */
108
    public function getCMSFields()
109
    {
110
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
111
            $fields->removeByName([
112
                'Images',
113
                'WeightModifier',
114
                'CodeModifier',
115
                'PriceModifier',
116
                'WeightModifierAction',
117
                'CodeModifierAction',
118
                'PriceModifierAction',
119
                'Available',
120
                'Type',
121
                'OptionModifierKey',
122
                'SortOrder',
123
                'ProductID',
124
            ]);
125
126
            $fields->insertBefore(
127
                'Content',
128
                CheckboxField::create('Available')
129
                    ->setTitle('Available for purchase')
130
            );
131
132
            $fields->insertBefore(
133
                'Content',
134
                $fields->dataFieldByName('VariationTypeID')
135
            );
136
137
            $fields->insertBefore(
138
                'Content',
139
                $fields->dataFieldByName('UseProductContent')
140
            );
141
142
            $content = $fields->dataFieldByName('Content');
143
144
            $content->hideUnless('UseProductContent')->isNotChecked()->end();
145
146
            if ($this->exists()) {
147
                $fields->addFieldToTab(
148
                    'Root.ProductModifications',
149
                    ReadonlyField::create('OptionModifierKey')
150
                        ->setTitle(_t('Variation.ModifierKey', 'Modifier Key'))
151
                );
152
            }
153
154
            $fields->addFieldsToTab(
155
                'Root.ProductModifications',
156
                [
157
                    FieldGroup::create(
158
                        DropdownField::create(
159
                            'WeightModifierAction',
160
                            _t('Variation.WeightModifierAction', 'Weight Modification Type'),
161
                            [
162
                                'Add' => _t(
163
                                    'Variation.WeightAdd',
164
                                    'Add to Base Weight',
165
                                    'Add to weight'
166
                                ),
167
                                'Subtract' => _t(
168
                                    'Variation.WeightSubtract',
169
                                    'Subtract from Base Weight',
170
                                    'Subtract from weight'
171
                                ),
172
                                'Set' => _t('Variation.WeightSet', 'Set as a new Weight'),
173
                            ]
174
                        )
175
                            ->setEmptyString('')
176
                            ->setDescription(_t(
177
                                'Variation.WeightDescription',
178
                                'Does weight modify or replace base weight?'
179
                            )),
180
                        NumericField::create("WeightModifier")
181
                            ->setTitle(_t('Variation.WeightModifier', 'Weight'))
182
                            ->setScale(3)
183
                            ->setDescription(_t(
184
                                'Variation.WeightDescription',
185
                                'Only supports up to 3 decimal places'
186
                            ))->displayIf('WeightModifierAction')->isNotEmpty()->end()
187
                    )->setTitle('Weight Modification'),
188
189
                    // Price Modifier Fields
190
                    //HeaderField::create('PriceHD', _t('Variation.PriceHD', 'Modify Price'), 4),
191
                    FieldGroup::create(
192
                        DropdownField::create(
193
                            'PriceModifierAction',
194
                            _t('Variation.PriceModifierAction', 'Price Modification Type'),
195
                            [
196
                                'Add' => _t(
197
                                    'Variation.PriceAdd',
198
                                    'Add to Base Price',
199
                                    'Add to price'
200
                                ),
201
                                'Subtract' => _t(
202
                                    'Variation.PriceSubtract',
203
                                    'Subtract from Base Price',
204
                                    'Subtract from price'
205
                                ),
206
                                'Set' => _t('Variation.PriceSet', 'Set as a new Price'),
207
                            ]
208
                        )
209
                            ->setEmptyString('')
210
                            ->setDescription(_t('Variation.PriceDescription', 'Does price modify or replace base price?')),
211
                        CurrencyField::create('PriceModifier')
212
                            ->setTitle(_t('Variation.PriceModifier', 'Price'))
213
                            ->displayIf('PriceModifierAction')->isNotEmpty()->end()
214
                    )->setTitle('Price Modifications'),
215
216
                    // Code Modifier Fields
217
                    //HeaderField::create('CodeHD', _t('Variation.CodeHD', 'Modify Code'), 4),
218
                    FieldGroup::create(
219
                        DropdownField::create(
220
                            'CodeModifierAction',
221
                            _t('Variation.CodeModifierAction', 'Code Modification Type'),
222
                            [
223
                                'Add' => _t(
224
                                    'Variation.CodeAdd',
225
                                    'Add to Base Code',
226
                                    'Add to code'
227
                                ),
228
                                'Subtract' => _t(
229
                                    'Variation.CodeSubtract',
230
                                    'Subtract from Base Code',
231
                                    'Subtract from code'
232
                                ),
233
                                'Set' => _t('Variation.CodeSet', 'Set as a new Code'),
234
                            ]
235
                        )
236
                            ->setEmptyString('')
237
                            ->setDescription(_t('Variation.CodeDescription', 'Does code modify or replace base code?')),
238
                        TextField::create('CodeModifier')
239
                            ->setTitle(_t('Variation.CodeModifier', 'Code'))
240
                            ->displayIf('CodeModifierAction')->isNotEmpty()->end()
241
                    )->setTitle('Code Modification'),
242
                ]
243
            );
244
245
            // Images tab
246
            $images = SortableUploadField::create('Images')
247
                ->setSortColumn('SortOrder')
248
                ->setIsMultiUpload(true)
249
                ->setAllowedExtensions($this->config()->get('allowed_images_extensions'))
250
                ->setFolderName('Uploads/Products/Images');
251
252
            $fields->addFieldsToTab('Root.Images', [
253
                $images,
254
            ]);
255
        });
256
257
        return parent::getCMSFields();
258
    }
259
260
    /**
261
     *
262
     */
263
    public function onBeforeWrite()
264
    {
265
        parent::onBeforeWrite();
266
267
        $modifierKeyField = 'OptionModifierKey';
268
        $this->{$modifierKeyField} = $this->getGeneratedValue();
269
270
        $codeModifierField = 'CodeModifier';
271
        switch ($this->CodeModifierAction) {
0 ignored issues
show
Bug Best Practice introduced by
The property CodeModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
272
            case 'Subtract':
273
            case 'Add':
274
                if ($this->config()->get('trimAllWhitespace') == false) {
275
                    // trim the right of the code - some companies use spaces to denote options
276
                    $trimmed = rtrim($this->{$codeModifierField});
277
                    // replace duplicate spaces
278
                    $this->{$codeModifierField} = preg_replace('/\s+/', ' ', $trimmed);
279
                    break;
280
                }
281
            /* falls through */
282
            case 'Set':
283
                $trimmed = trim($this->{$codeModifierField});
284
                $this->{$codeModifierField} = preg_replace('/\s+/', ' ', $trimmed);
285
                break;
286
        }
287
    }
288
289
    /**
290
     * @return ValidationResult
291
     */
292
    public function validate()
293
    {
294
        $validate = parent::validate();
295
296
        if (!$this->Title) {
297
            $validate->addFieldError('Title', 'A title is required');
298
        }
299
300
        if (!$this->VariationTypeID) {
0 ignored issues
show
Bug Best Practice introduced by
The property VariationTypeID does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
301
            $validate->addFieldError('VariationTypeID', 'A variation type is required');
302
        }
303
304
        return $validate;
305
    }
306
307
    /**
308
     * @return string
309
     */
310
    public function getGeneratedValue()
311
    {
312
        $modPrice = ($this->PriceModifier) ? (string)$this->PriceModifier : '0';
0 ignored issues
show
Bug Best Practice introduced by
The property PriceModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
313
        $modPriceWithSymbol = self::getOptionModifierActionSymbol($this->PriceModifierAction) . $modPrice;
0 ignored issues
show
Bug Best Practice introduced by
The property PriceModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
314
        $modWeight = ($this->WeightModifier) ? (string)$this->WeightModifier : '0';
0 ignored issues
show
Bug Best Practice introduced by
The property WeightModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
315
        $modWeight = self::getOptionModifierActionSymbol($this->WeightModifierAction) . $modWeight;
0 ignored issues
show
Bug Best Practice introduced by
The property WeightModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
316
        $modCode = self::getOptionModifierActionSymbol($this->CodeModifierAction) . $this->CodeModifier;
0 ignored issues
show
Bug Best Practice introduced by
The property CodeModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property CodeModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
317
318
        return $this->Title . '{p' . $modPriceWithSymbol . '|w' . $modWeight . '|c' . $modCode . '}';
319
    }
320
321
    /**
322
     * @param $oma
323
     * @param bool $returnWithOnlyPlusMinus
324
     *
325
     * @return string
326
     */
327
    public static function getOptionModifierActionSymbol($oma, $returnWithOnlyPlusMinus = false)
328
    {
329
        switch ($oma) {
330
            case 'Subtract':
331
                $symbol = '-';
332
                break;
333
            case 'Set':
334
                $symbol = ($returnWithOnlyPlusMinus) ? '' : ':';
335
                break;
336
            default:
337
                $symbol = '+';
338
        }
339
340
        return $symbol;
341
    }
342
343
    /**
344
     * @return string
345
     */
346
    protected function getWeightModifierWithSymbol()
347
    {
348
        return $this->getOptionModifierActionSymbol($this->WeightModifierAction) . $this->WeightModifier;
0 ignored issues
show
Bug Best Practice introduced by
The property WeightModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property WeightModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
349
    }
350
351
    /**
352
     * @return string
353
     */
354
    protected function getPriceModifierWithSymbol()
355
    {
356
        return $this->getOptionModifierActionSymbol($this->PriceModifierAction) . $this->PriceModifier;
0 ignored issues
show
Bug Best Practice introduced by
The property PriceModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property PriceModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
357
    }
358
359
    /**
360
     * @return string
361
     */
362
    protected function getCodeModifierWithSymbol()
363
    {
364
        return $this->getOptionModifierActionSymbol($this->CodeModifierAction) . $this->CodeModifier;
0 ignored issues
show
Bug Best Practice introduced by
The property CodeModifierAction does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property CodeModifier does not exist on Dynamic\Foxy\Model\Variation. Since you implemented __get, consider adding a @property annotation.
Loading history...
365
    }
366
}
367