Completed
Pull Request — master (#287)
by Nic
07:49
created

FoxyStripeProduct::getDiscountFieldValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
c 0
b 0
f 0
ccs 0
cts 7
cp 0
rs 9.6666
cc 2
eloc 6
nc 2
nop 0
crap 6
1
<?php
2
3
/**
4
 * Class ProductPage
5
 * @package foxystripe
6
 * @property string $Title
7
 * @property HTMLText $Content
8
 */
9
class FoxyStripeProduct extends DataObject
10
{
11
12
    /**
13
     * @var string
14
     */
15
    private static $singular_name = 'Product';
16
    /**
17
     * @var string
18
     */
19
    private static $plural_name = 'Products';
20
    /**
21
     * @var string
22
     */
23
    private static $description = 'A product that can be added to the shopping cart';
24
25
    /**
26
     * @var array
27
     */
28
    private static $db = [
29
        'Price' => 'Currency',
30
        'Code' => 'Varchar(100)',
31
        'ReceiptTitle' => 'HTMLVarchar(255)',
32
        'Featured' => 'Boolean',
33
        'Available' => 'Boolean',
34
        'DiscountTitle' => 'Varchar(50)'
35
    ];
36
37
    /**
38
     * @var array
39
     */
40
    private static $has_one = [
41
        'PreviewImage' => 'Image',
42
        'Category' => 'FoxyCartProductCategory'
43
    ];
44
45
    /**
46
     * @var array
47
     */
48
    private static $has_many = [
49
        'ProductImages' => 'ProductImage',
50
        'ProductOptions' => 'OptionItem',
51
        'OrderDetails' => 'OrderDetail',
52
        'ProductDiscountTiers' => 'ProductDiscountTier'
53
    ];
54
55
    /**
56
     * @var array
57
     */
58
    private static $belongs_many_many = [
59
        'ProductHolders' => 'ProductHolder'
60
    ];
61
62
    /**
63
     * @var array
64
     */
65
    private static $indexes = [
66
        'Code' => true,
67
    ];
68
69
    /**
70
     * @var array
71
     */
72
    private static $defaults = [
73
        'ShowInMenus' => false,
74
        'Available' => true,
75
        'Weight' => '1.0'
76
    ];
77
78
    /**
79
     * @var array
80
     */
81
    private static $summary_fields = [
82
        'Title',
83
        'Code',
84
        'Price.Nice',
85
        'Category.Title'
86
    ];
87
88
    /**
89
     * @var array
90
     */
91
    private static $searchable_fields = [
92
        'Title',
93
        'Code',
94
        'Featured',
95
        'Available',
96
        'Category.ID'
97
    ];
98
99
    public function fieldLabels($includeRelations = true)
100
    {
101
        $labels = parent::fieldLabels($includeRelations);
102
103
        $labels['Title'] = _t('ProductPage.TitleLabel', 'Name');
104
        $labels['Code'] = _t('ProductPage.CodeLabel', "Code");
105
        $labels['Price.Nice'] = _t('ProductPage.PriceLabel', 'Price');
106
        $labels['Featured.Nice'] = _t('ProductPage.NiceLabel', 'Featured');
107
        $labels['Available.Nice'] = _t('ProductPage.AvailableLabel', 'Available');
108
        $labels['Category.ID'] = _t('ProductPage.IDLabel', 'Category');
109
        $labels['Category.Title'] = _t('ProductPage.CategoryTitleLabel', 'Category');
110
111
        return $labels;
112
    }
113
114
    /**
115
     * @return FieldList
116
     */
117
    public function getCMSFields()
118
    {
119
        $fields = parent::getCMSFields();
120
121
        // allow extensions of ProductPage to override the PreviewImage field description
122
        $previewDescription = ($this->stat('customPreviewDescription')) ? $this->stat('customPreviewDescription') : _t('ProductPage.PreviewImageDescription', 'Image used throughout site to represent this product');
123
124
        // Cateogry Dropdown field w/ add new
125
        $source = function () {
126
            return FoxyCartProductCategory::get()->map()->toArray();
127
        };
128
        $catField = DropdownField::create('CategoryID', _t('ProductPage.Category', 'FoxyCart Category'), $source())
129
            ->setEmptyString('')
130
            ->setDescription(_t(
131
                'ProductPage.CategoryDescription',
132
                'Required, must also exist in
133
                    <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">
134
                        FoxyCart Categories
135
                    </a>.
136
                    Used to set category specific options like shipping and taxes. Managed in
137
                        <a href="admin/settings">
138
                            Settings > FoxyStripe > Categories
139
                        </a>'
140
            ));
141
        if (class_exists('QuickAddNewExtension')) $catField->useAddNew('FoxyCartProductCategory', $source);
142
143
        // Product Images gridfield
144
        $config = GridFieldConfig_RelationEditor::create();
145
        if (class_exists('GridFieldSortableRows')) $config->addComponent(new GridFieldSortableRows('SortOrder'));
146
        if (class_exists('GridFieldBulkImageUpload')) {
147
            $config->addComponent(new GridFieldBulkUpload());
148
            $config->getComponentByType('GridFieldBulkUpload')->setUfConfig('folderName', 'Uploads/ProductImages');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setUfConfig() does only exist in the following implementations of said interface: GridFieldBulkImageUpload, GridFieldBulkUpload.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
149
        }
150
        $prodImagesField = GridField::create(
151
            'ProductImages',
152
            _t('ProductPage.ProductImages', 'Images'),
153
            $this->ProductImages(),
0 ignored issues
show
Documentation Bug introduced by
The method ProductImages does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
154
            $config
155
        );
156
157
        // Product Options field
158
        $config = GridFieldConfig_RelationEditor::create();
159
        if (class_exists('GridFieldSortableRows')) {
160
            $config->addComponent(new GridFieldSortableRows('SortOrder'));
161
            $products = $this->ProductOptions()->sort('SortOrder');
0 ignored issues
show
Documentation Bug introduced by
The method ProductOptions does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
162
        } else {
163
            $products = $this->ProductOptions();
0 ignored issues
show
Documentation Bug introduced by
The method ProductOptions does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
164
        }
165
        $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
166
        $prodOptField = GridField::create(
167
            'ProductOptions',
168
            _t('ProductPage.ProductOptions', 'Options'),
169
            $products,
170
            $config
171
        );
172
173
        // Details tab
174
        $fields->addFieldsToTab('Root.Details', [
175
            HeaderField::create('DetailHD', 'Product Details', 2),
176
            CheckboxField::create('Available')
177
                ->setTitle(_t('ProductPage.Available', 'Available for purchase'))
178
                ->setDescription(_t(
179
                    'ProductPage.AvailableDescription',
180
                    'If unchecked, will remove "Add to Cart" form and instead display "Currently unavailable"'
181
                )),
182
            TextField::create('Code')
183
                ->setTitle(_t('ProductPage.Code', 'Product Code'))
184
                ->setDescription(_t(
185
                    'ProductPage.CodeDescription',
186
                    'Required, must be unique. Product identifier used by FoxyCart in transactions'
187
                )),
188
            $catField,
189
            CurrencyField::create('Price')
190
                ->setTitle(_t('ProductPage.Price', 'Price'))
191
                ->setDescription(_t(
192
                    'ProductPage.PriceDescription',
193
                    'Base price for this product. Can be modified using Product Options'
194
                )),
195
            NumericField::create('Weight')
196
                ->setTitle(_t('ProductPage.Weight', 'Weight'))
197
                ->setDescription(_t(
198
                    'ProductPage.WeightDescription',
199
                    'Base weight for this product in lbs. Can be modified using Product Options'
200
                )),
201
            CheckboxField::create('Featured')
202
                ->setTitle(_t('ProductPage.Featured', 'Featured Product')),
203
            TextField::create('ReceiptTitle')
204
                ->setTitle(_t('ProductPage.ReceiptTitle', 'Product Title for Receipt'))
205
                ->setDescription(_t(
206
                    'ProductPage.ReceiptTitleDescription', 'Optional'
207
                ))
208
        ]);
209
210
        // Images tab
211
        $fields->addFieldsToTab('Root.Images', [
212
            HeaderField::create('MainImageHD', _t('ProductPage.MainImageHD', 'Product Image'), 2),
213
            UploadField::create('PreviewImage', '')
214
                ->setDescription($previewDescription)
215
                ->setFolderName('Uploads/Products')
216
                ->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png'])
217
                ->setAllowedMaxFileNumber(1),
218
            HeaderField::create('ProductImagesHD', _t('ProductPage.ProductImagesHD' . 'Product Image Gallery'), 2),
219
            $prodImagesField
220
                ->setDescription(_t(
221
                    'ProductPage.ProductImagesDescription',
222
                    'Additional Product Images, shown in gallery on Product page'
223
                ))
224
        ]);
225
226
        // Options Tab
227
        $fields->addFieldsToTab('Root.Options', [
228
            HeaderField::create('OptionsHD', _t('ProductPage.OptionsHD', 'Product Options'), 2),
229
            LiteralField::create('OptionsDescrip', _t(
230
                'Page.OptionsDescrip',
231
                '<p>Product Options allow products to be customized by attributes such as size or color.
232
                    Options can also modify the product\'s price, weight or code.</p>'
233
            )),
234
            $prodOptField
235
        ]);
236
237
        if (!$this->DiscountTitle && $this->ProductDiscountTiers()->exists()) {
0 ignored issues
show
Documentation introduced by
The property DiscountTitle does not exist on object<FoxyStripeProduct>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation Bug introduced by
The method ProductDiscountTiers does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
238
            $fields->addFieldTotab('Root.Discounts', new LiteralField("ProductDiscountHeaderWarning", "<p class=\"message warning\">A discount title is required for FoxyCart to properly parse the value. The discounts will not be applied until a title is entered.</p>"));
239
        }
240
241
        $fields->addFieldToTab('Root.Discounts', TextField::create('DiscountTitle')->setTitle(_t('Product.DiscountTitle', 'Discount Title')));
242
        $discountsConfig = GridFieldConfig_RelationEditor::create();
243
        $discountsConfig->removeComponentsByType('GridFieldAddExistingAutocompleter');
244
        $discountsConfig->removeComponentsByType('GridFieldDeleteAction');
245
        $discountsConfig->addComponent(new GridFieldDeleteAction(false));
246
        $discountGrid = GridField::create('ProductDiscountTiers', 'Product Discounts', $this->ProductDiscountTiers(), $discountsConfig);
0 ignored issues
show
Documentation Bug introduced by
The method ProductDiscountTiers does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
247
        $fields->addFieldToTab('Root.Discounts', $discountGrid);
248
249 View Code Duplication
        if (FoxyCart::store_name_warning() !== null) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
250
            $fields->addFieldToTab('Root.Main', LiteralField::create("StoreSubDomainHeaderWarning", _t(
251
                'ProductPage.StoreSubDomainHeaderWarning',
252
                "<p class=\"message error\">Store sub-domain must be entered in the <a href=\"/admin/settings/\">site settings</a></p>"
253
            )), 'Title');
254
        }
255
256
        // allows CMS fields to be extended
257
        $this->extend('updateCMSFields', $fields);
258
259
        return $fields;
260
    }
261
262 33
    public function onBeforeWrite()
263
    {
264 33
        parent::onBeforeWrite();
265 33
        if (!$this->CategoryID) {
0 ignored issues
show
Documentation introduced by
The property CategoryID does not exist on object<FoxyStripeProduct>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
266
            $default = FoxyCartProductCategory::get()->filter(['Code' => 'DEFAULT'])->first();
267
            $this->CategoryID = $default->ID;
0 ignored issues
show
Documentation introduced by
The property CategoryID does not exist on object<FoxyStripeProduct>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
268
        }
269
270
        //update many_many lists when multi-group is on
271 33
        if (SiteConfig::current_site_config()->MultiGroup) {
272
            $holders = $this->ProductHolders();
0 ignored issues
show
Documentation Bug introduced by
The method ProductHolders does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
273
            $product = ProductPage::get()->byID($this->ID);
274
            if (isset($product->ParentID)) {
275
                $origParent = $product->ParentID;
276
            } else {
277
                $origParent = null;
278
            }
279
            $currentParent = $this->ParentID;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<FoxyStripeProduct>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
280
            if ($origParent != $currentParent) {
281
                if ($holders->find('ID', $origParent)) {
282
                    $holders->removeByID($origParent);
283
                }
284
285
            }
286
            $holders->add($currentParent);
287
        }
288
289 33
        $title = ltrim($this->Title);
290 33
        $title = rtrim($title);
291 33
        $this->Title = $title;
292
293
294 33
    }
295
296 33
    public function onAfterWrite()
297
    {
298 33
        parent::onAfterWrite();
299
300
301 33
    }
302
303 1
    public function onBeforeDelete()
304
    {
305 1
        if ($this->Status != "Published") {
0 ignored issues
show
Documentation introduced by
The property Status does not exist on object<FoxyStripeProduct>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
306 1
            if ($this->ProductOptions()) {
0 ignored issues
show
Documentation Bug introduced by
The method ProductOptions does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
307 1
                $options = $this->getComponents('ProductOptions');
308 1
                foreach ($options as $option) {
309
                    $option->delete();
310 1
                }
311 1
            }
312 1
            if ($this->ProductImages()) {
0 ignored issues
show
Documentation Bug introduced by
The method ProductImages does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
313
                //delete product image dataobjects, not the images themselves.
314 1
                $images = $this->getComponents('ProductImages');
315 1
                foreach ($images as $image) {
316
                    $image->delete();
317 1
                }
318 1
            }
319 1
        }
320 1
        parent::onBeforeDelete();
321 1
    }
322
323 8
    public function validate()
324
    {
325 8
        $result = parent::validate();
326
327
        /*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...
328
            if($this->Price <= 0) {
329
                $result->error('Must set a positive price value');
330
            }
331
            if($this->Weight <= 0){
332
                $result->error('Must set a positive weight value');
333
            }
334
            if($this->Code == ''){
335
                $result->error('Must set a product code');
336
            }
337
        }*/
338
339 8
        return $result;
340
    }
341
342
    public function getCMSValidator()
343
    {
344
        return new RequiredFields(['CategoryID', 'Price', 'Code']);
345
    }
346
347
    public static function getGeneratedValue($productCode = null, $optionName = null, $optionValue = null, $method = 'name', $output = false, $urlEncode = false)
348
    {
349
        $optionName = ($optionName !== null) ? preg_replace('/\s/', '_', $optionName) : $optionName;
350
        return (SiteConfig::current_site_config()->CartValidation)
351
            ? FoxyCart_Helper::fc_hash_value($productCode, $optionName, $optionValue, $method, $output, $urlEncode) :
352
            $optionValue;
353
    }
354
355
    /**
356
     * @return HTMLText
357
     */
358
    public function getCartScript()
359
    {
360
        return $this->customise(['StoreName' => FoxyCart::get_foxy_cart_store_name()])->renderWith('FoxyCartScript');
361
    }
362
363
    public function getDiscountFieldValue()
364
    {
365
        $tiers = $this->ProductDiscountTiers();
0 ignored issues
show
Documentation Bug introduced by
The method ProductDiscountTiers does not exist on object<FoxyStripeProduct>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
366
        $bulkString = '';
367
        foreach ($tiers as $tier) {
368
            $bulkString .= "|{$tier->Quantity}-{$tier->Percentage}";
369
        }
370
        return "{$this->Title}{allunits{$bulkString}}";
371
    }
372
373
    /**
374
     * @return FoxyStripePurchaseForm
375
     */
376
    public function getPurchaseForm()
377
    {
378
379
        $product = $this;
380
381
        $form = FoxyStripePurchaseForm::create(Controller::curr(), __FUNCTION__, null, null, null, $product);
382
383
        $this->extend('updateFoxyStripePurchaseForm', $form);
384
385
        return $form;
386
387
    }
388
389
}