Completed
Pull Request — master (#287)
by Nic
08:29
created

FoxyStripeProduct::validate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 1
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
        'Title' => 'Varchar(255)',
30
        'Content' => 'HTMLText',
31
        'Price' => 'Currency',
32
        'Code' => 'Varchar(100)',
33
        'ReceiptTitle' => 'HTMLVarchar(255)',
34
        'Featured' => 'Boolean',
35
        'Available' => 'Boolean',
36
        'DiscountTitle' => 'Varchar(50)'
37
    ];
38
39
    /**
40
     * @var array
41
     */
42
    private static $has_one = [
43
        'PreviewImage' => 'Image',
44
        'Category' => 'FoxyCartProductCategory'
45
    ];
46
47
    /**
48
     * @var array
49
     */
50
    private static $has_many = [
51
        'ProductImages' => 'ProductImage',
52
        'ProductOptions' => 'OptionItem',
53
        'OrderDetails' => 'OrderDetail',
54
        'ProductDiscountTiers' => 'ProductDiscountTier'
55
    ];
56
57
    /**
58
     * @var array
59
     */
60
    private static $belongs_many_many = [
61
        'ProductHolders' => 'ProductHolder'
62
    ];
63
64
    /**
65
     * @var array
66
     */
67
    private static $indexes = [
68
        'Code' => true,
69
    ];
70
71
    /**
72
     * @var array
73
     */
74
    private static $defaults = [
75
        'ShowInMenus' => false,
76
        'Available' => true,
77
        'Weight' => '1.0'
78
    ];
79
80
    /**
81
     * @var array
82
     */
83
    private static $summary_fields = [
84
        'Title',
85
        'Code',
86
        'Price.Nice',
87
        'Category.Title'
88
    ];
89
90
    /**
91
     * @var array
92
     */
93
    private static $searchable_fields = [
94
        'Title',
95
        'Code',
96
        'Featured',
97
        'Available',
98
        'Category.ID'
99
    ];
100
101
    public function fieldLabels($includeRelations = true)
102
    {
103
        $labels = parent::fieldLabels($includeRelations);
104
105
        $labels['Title'] = _t('ProductPage.TitleLabel', 'Name');
106
        $labels['Code'] = _t('ProductPage.CodeLabel', "Code");
107
        $labels['Price.Nice'] = _t('ProductPage.PriceLabel', 'Price');
108
        $labels['Featured.Nice'] = _t('ProductPage.NiceLabel', 'Featured');
109
        $labels['Available.Nice'] = _t('ProductPage.AvailableLabel', 'Available');
110
        $labels['Category.ID'] = _t('ProductPage.IDLabel', 'Category');
111
        $labels['Category.Title'] = _t('ProductPage.CategoryTitleLabel', 'Category');
112
113
        return $labels;
114
    }
115
116
    /**
117
     * @return FieldList
118
     */
119
    public function getCMSFields()
120
    {
121
        $fields = parent::getCMSFields();
122
123
        // allow extensions of ProductPage to override the PreviewImage field description
124
        $previewDescription = ($this->stat('customPreviewDescription')) ? $this->stat('customPreviewDescription') : _t('ProductPage.PreviewImageDescription', 'Image used throughout site to represent this product');
125
126
        // Cateogry Dropdown field w/ add new
127
        $source = function () {
128
            return FoxyCartProductCategory::get()->map()->toArray();
129
        };
130
        $catField = DropdownField::create('CategoryID', _t('ProductPage.Category', 'FoxyCart Category'), $source())
131
            ->setEmptyString('')
132
            ->setDescription(_t(
133
                'ProductPage.CategoryDescription',
134
                'Required, must also exist in
135
                    <a href="https://admin.foxycart.com/admin.php?ThisAction=ManageProductCategories" target="_blank">
136
                        FoxyCart Categories
137
                    </a>.
138
                    Used to set category specific options like shipping and taxes. Managed in
139
                        <a href="admin/settings">
140
                            Settings > FoxyStripe > Categories
141
                        </a>'
142
            ));
143
        if (class_exists('QuickAddNewExtension')) $catField->useAddNew('FoxyCartProductCategory', $source);
144
145
        // Product Images gridfield
146
        $config = GridFieldConfig_RelationEditor::create();
147
        if (class_exists('GridFieldSortableRows')) $config->addComponent(new GridFieldSortableRows('SortOrder'));
148
        if (class_exists('GridFieldBulkImageUpload')) {
149
            $config->addComponent(new GridFieldBulkUpload());
150
            $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...
151
        }
152
        $prodImagesField = GridField::create(
153
            'ProductImages',
154
            _t('ProductPage.ProductImages', 'Images'),
155
            $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...
156
            $config
157
        );
158
159
        // Product Options field
160
        $config = GridFieldConfig_RelationEditor::create();
161
        if (class_exists('GridFieldSortableRows')) {
162
            $config->addComponent(new GridFieldSortableRows('SortOrder'));
163
            $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...
164
        } else {
165
            $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...
166
        }
167
        $config->removeComponentsByType('GridFieldAddExistingAutocompleter');
168
        $prodOptField = GridField::create(
169
            'ProductOptions',
170
            _t('ProductPage.ProductOptions', 'Options'),
171
            $products,
172
            $config
173
        );
174
175
        // Details tab
176
        $fields->addFieldsToTab('Root.Details', [
177
            HeaderField::create('DetailHD', 'Product Details', 2),
178
            CheckboxField::create('Available')
179
                ->setTitle(_t('ProductPage.Available', 'Available for purchase'))
180
                ->setDescription(_t(
181
                    'ProductPage.AvailableDescription',
182
                    'If unchecked, will remove "Add to Cart" form and instead display "Currently unavailable"'
183
                )),
184
            TextField::create('Code')
185
                ->setTitle(_t('ProductPage.Code', 'Product Code'))
186
                ->setDescription(_t(
187
                    'ProductPage.CodeDescription',
188
                    'Required, must be unique. Product identifier used by FoxyCart in transactions'
189
                )),
190
            $catField,
191
            CurrencyField::create('Price')
192
                ->setTitle(_t('ProductPage.Price', 'Price'))
193
                ->setDescription(_t(
194
                    'ProductPage.PriceDescription',
195
                    'Base price for this product. Can be modified using Product Options'
196
                )),
197
            NumericField::create('Weight')
198
                ->setTitle(_t('ProductPage.Weight', 'Weight'))
199
                ->setDescription(_t(
200
                    'ProductPage.WeightDescription',
201
                    'Base weight for this product in lbs. Can be modified using Product Options'
202
                )),
203
            CheckboxField::create('Featured')
204
                ->setTitle(_t('ProductPage.Featured', 'Featured Product')),
205
            TextField::create('ReceiptTitle')
206
                ->setTitle(_t('ProductPage.ReceiptTitle', 'Product Title for Receipt'))
207
                ->setDescription(_t(
208
                    'ProductPage.ReceiptTitleDescription', 'Optional'
209
                ))
210
        ]);
211
212
        // Images tab
213
        $fields->addFieldsToTab('Root.Images', [
214
            HeaderField::create('MainImageHD', _t('ProductPage.MainImageHD', 'Product Image'), 2),
215
            UploadField::create('PreviewImage', '')
216
                ->setDescription($previewDescription)
217
                ->setFolderName('Uploads/Products')
218
                ->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png'])
219
                ->setAllowedMaxFileNumber(1),
220
            HeaderField::create('ProductImagesHD', _t('ProductPage.ProductImagesHD' . 'Product Image Gallery'), 2),
221
            $prodImagesField
222
                ->setDescription(_t(
223
                    'ProductPage.ProductImagesDescription',
224
                    'Additional Product Images, shown in gallery on Product page'
225
                ))
226
        ]);
227
228
        // Options Tab
229
        $fields->addFieldsToTab('Root.Options', [
230
            HeaderField::create('OptionsHD', _t('ProductPage.OptionsHD', 'Product Options'), 2),
231
            LiteralField::create('OptionsDescrip', _t(
232
                'Page.OptionsDescrip',
233
                '<p>Product Options allow products to be customized by attributes such as size or color.
234
                    Options can also modify the product\'s price, weight or code.</p>'
235
            )),
236
            $prodOptField
237
        ]);
238
239
        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...
240
            $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>"));
241
        }
242
243
        $fields->addFieldToTab('Root.Discounts', TextField::create('DiscountTitle')->setTitle(_t('Product.DiscountTitle', 'Discount Title')));
244
        $discountsConfig = GridFieldConfig_RelationEditor::create();
245
        $discountsConfig->removeComponentsByType('GridFieldAddExistingAutocompleter');
246
        $discountsConfig->removeComponentsByType('GridFieldDeleteAction');
247
        $discountsConfig->addComponent(new GridFieldDeleteAction(false));
248
        $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...
249
        $fields->addFieldToTab('Root.Discounts', $discountGrid);
250
251 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...
252
            $fields->addFieldToTab('Root.Main', LiteralField::create("StoreSubDomainHeaderWarning", _t(
253
                'ProductPage.StoreSubDomainHeaderWarning',
254
                "<p class=\"message error\">Store sub-domain must be entered in the <a href=\"/admin/settings/\">site settings</a></p>"
255
            )), 'Title');
256
        }
257
258
        // allows CMS fields to be extended
259
        $this->extend('updateCMSFields', $fields);
260
261
        return $fields;
262
    }
263
264 28
    public function onBeforeWrite()
265
    {
266 28
        parent::onBeforeWrite();
267 28
        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...
268
            $default = FoxyCartProductCategory::get()->filter(['Code' => 'DEFAULT'])->first();
269
            $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...
270
        }
271
272
        //update many_many lists when multi-group is on
273 28
        if (SiteConfig::current_site_config()->MultiGroup) {
274
            $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...
275
            $product = ProductPage::get()->byID($this->ID);
276
            if (isset($product->ParentID)) {
277
                $origParent = $product->ParentID;
278
            } else {
279
                $origParent = null;
280
            }
281
            $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...
282
            if ($origParent != $currentParent) {
283
                if ($holders->find('ID', $origParent)) {
284
                    $holders->removeByID($origParent);
285
                }
286
287
            }
288
            $holders->add($currentParent);
289
        }
290
291 28
        $title = ltrim($this->Title);
292 28
        $title = rtrim($title);
293 28
        $this->Title = $title;
294
295
296 28
    }
297
298 28
    public function onAfterWrite()
299
    {
300 28
        parent::onAfterWrite();
301
302
303 28
    }
304
305 1
    public function onBeforeDelete()
306
    {
307 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...
308 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...
309 1
                $options = $this->getComponents('ProductOptions');
310 1
                foreach ($options as $option) {
311
                    $option->delete();
312 1
                }
313 1
            }
314 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...
315
                //delete product image dataobjects, not the images themselves.
316 1
                $images = $this->getComponents('ProductImages');
317 1
                foreach ($images as $image) {
318
                    $image->delete();
319 1
                }
320 1
            }
321 1
        }
322 1
        parent::onBeforeDelete();
323 1
    }
324
325 8
    public function validate()
326
    {
327 8
        $result = parent::validate();
328
329
        /*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...
330
            if($this->Price <= 0) {
331
                $result->error('Must set a positive price value');
332
            }
333
            if($this->Weight <= 0){
334
                $result->error('Must set a positive weight value');
335
            }
336
            if($this->Code == ''){
337
                $result->error('Must set a product code');
338
            }
339
        }*/
340
341 8
        return $result;
342
    }
343
344
    public function getCMSValidator()
345
    {
346
        return new RequiredFields(['CategoryID', 'Price', 'Weight', 'Code']);
347
    }
348
349
    public static function getGeneratedValue($productCode = null, $optionName = null, $optionValue = null, $method = 'name', $output = false, $urlEncode = false)
350
    {
351
        $optionName = ($optionName !== null) ? preg_replace('/\s/', '_', $optionName) : $optionName;
352
        return (SiteConfig::current_site_config()->CartValidation)
353
            ? FoxyCart_Helper::fc_hash_value($productCode, $optionName, $optionValue, $method, $output, $urlEncode) :
354
            $optionValue;
355
    }
356
357
    // get FoxyCart Store Name for JS call
358
    public function getCartScript()
359
    {
360
        return '<script src="https://cdn.foxycart.com/' . FoxyCart::getFoxyCartStoreName() . '/loader.js" async defer></script>';
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
}