Passed
Push — 1.3 ( 47b397...4f928d )
by Morven
04:11
created

LineItem::Match()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 12
c 1
b 0
f 0
nc 6
nop 3
dl 0
loc 22
rs 8.8333
1
<?php
2
3
namespace SilverCommerce\OrdersAdmin\Model;
4
5
use SilverStripe\i18n\i18n;
6
use SilverStripe\ORM\DataObject;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\Forms\DropdownField;
9
use SilverStripe\Forms\ReadonlyField;
10
use SilverStripe\SiteConfig\SiteConfig;
11
use SilverCommerce\TaxAdmin\Model\TaxRate;
12
use SilverCommerce\TaxAdmin\Traits\Taxable;
13
use SilverStripe\Core\Manifest\ModuleLoader;
14
use SilverStripe\Subsites\State\SubsiteState;
0 ignored issues
show
Bug introduced by
The type SilverStripe\Subsites\State\SubsiteState was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
15
use SilverStripe\Forms\GridField\GridFieldEditButton;
16
use SilverStripe\Forms\GridField\GridFieldDataColumns;
17
use SilverStripe\ORM\FieldType\DBHTMLText as HTMLText;
18
use SilverCommerce\TaxAdmin\Interfaces\TaxableProvider;
19
use SilverStripe\Forms\GridField\GridFieldAddNewButton;
20
use SilverStripe\Forms\GridField\GridFieldDeleteAction;
21
use Symbiote\GridFieldExtensions\GridFieldEditableColumns;
22
use Symbiote\GridFieldExtensions\GridFieldAddNewInlineButton;
23
use SilverStripe\Forms\GridField\GridFieldAddExistingAutocompleter;
24
25
/**
26
 * A LineItem is a single line item on an order, extimate or even in
27
 * the shopping cart.
28
 *
29
 * An item has a number of fields that describes a product:
30
 *
31
 * - Key: ID used to detect this item
32
 * - Title: Title of the item
33
 * - Content: Description of this object
34
 * - Quantity: Number or items in this order
35
 * - Weight: Weight of this item (unit of measurment is defined globally)
36
 * - TaxRate: Rate of tax for this item (e.g. 20.00 for 20%)
37
 * - ProductClass: ClassName of product that this item is matched against
38
 * - StockID: Unique identifier of this item (used with ProductClass
39
 *            match to a product)
40
 * - Locked: Is this a locked item? Locked items cannot be changed in the
41
 *           shopping cart
42
 * - Deliverable: Is this a product that can be delivered? This can effect
43
 *                delivery options
44
 *
45
 * @author Mo <[email protected]>
46
 */
47
class LineItem extends DataObject implements TaxableProvider
48
{
49
    use Taxable;
0 ignored issues
show
Bug introduced by
The trait SilverCommerce\TaxAdmin\Traits\Taxable requires the property $Rate which is not provided by SilverCommerce\OrdersAdmin\Model\LineItem.
Loading history...
50
51
    private static $table_name = 'LineItem';
52
53
    /**
54
     * The name of the param used on a related product to
55
     * track Stock Levels.
56
     *
57
     * Defaults to StockLevel
58
     *
59
     * @var string
60
     * @config
61
     */
62
    private static $stock_param = "StockLevel";
63
64
    /**
65
     * Standard database columns
66
     *
67
     * @var array
68
     * @config
69
     */
70
    private static $db = [
71
        "Key"           => "Varchar(255)",
72
        "Title"         => "Varchar",
73
        "BasePrice"     => "Decimal(9,3)",
74
        "Price"         => "Currency",
75
        "Quantity"      => "Int",
76
        "StockID"       => "Varchar(100)",
77
        "ProductClass"  => "Varchar",
78
        "Locked"        => "Boolean",
79
        "Stocked"       => "Boolean",
80
        "Deliverable"   => "Boolean"
81
    ];
82
83
    /**
84
     * Foreign key associations in DB
85
     *
86
     * @var array
87
     * @config
88
     */
89
    private static $has_one = [
90
        "Parent"      => Estimate::class,
91
        "Tax"         => TaxRate::class,
92
        "TaxRate"     => TaxRate::class
93
    ];
94
    
95
    /**
96
     * One to many associations
97
     *
98
     * @var array
99
     * @config
100
     */
101
    private static $has_many = [
102
        "Customisations" => LineItemCustomisation::class
103
    ];
104
105
    /**
106
     * Specify default values of a field
107
     *
108
     * @var array
109
     * @config
110
     */
111
    private static $defaults = [
112
        "Quantity"      => 1,
113
        "ProductClass"  => "Product",
114
        "Locked"        => false,
115
        "Stocked"       => false,
116
        "Deliverable"   => true
117
    ];
118
119
    /**
120
     * Function to DB Object conversions
121
     *
122
     * @var array
123
     * @config
124
     */
125
    private static $casting = [
126
        "UnitPrice" => "Currency(9,3)",
127
        "UnitTax" => "Currency(9,3)",
128
        "UnitTotal" => "Currency(9,3)",
129
        "SubTotal" => "Currency(9,3)",
130
        "TaxRate" => "Decimal",
131
        "TaxTotal" => "Currency(9,3)",
132
        "Total" => "Currency(9,3)",
133
        "CustomisationList" => "Text",
134
        "CustomisationAndPriceList" => "Text",
135
    ];
136
137
    /**
138
     * Fields to display in list tables
139
     *
140
     * @var array
141
     * @config
142
     */
143
    private static $summary_fields = [
144
        "Quantity",
145
        "Title",
146
        "StockID",
147
        "BasePrice",
148
        "TaxRateID",
149
        "CustomisationAndPriceList"
150
    ];
151
152
    private static $field_labels = [
153
        "BasePrice"=> "Item Price",
154
        "Price"    => "Item Price",
155
        "TaxID"    => "Tax",
156
        "TaxRateID"=> "Tax",
157
        "CustomisationAndPriceList" => "Customisations"
158
    ];
159
160
    /**
161
     * Get the basic price for this object
162
     *
163
     * @return float
164
     */
165
    public function getBasePrice()
166
    {
167
        return $this->dbObject('BasePrice')->getValue();
168
    }
169
170
    /**
171
     * Return the tax rate for this Object
172
     *
173
     * @return TaxRate
174
     */
175
    public function getTaxRate()
176
    {
177
        return $this->TaxRate();
0 ignored issues
show
Bug introduced by
The method TaxRate() does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

177
        return $this->/** @scrutinizer ignore-call */ TaxRate();
Loading history...
178
    }
179
180
    /**
181
     * Get the locale from the site
182
     *
183
     * @return string
184
     */
185
    public function getLocale()
186
    {
187
        return i18n::get_locale();
188
    }
189
190
    /**
191
     * Get should this field automatically show the price including TAX?
192
     *
193
     * @return bool
194
     */
195
    public function getShowPriceWithTax()
196
    {
197
        $config = SiteConfig::current_site_config();
198
        $show = $config->ShowPriceAndTax;
199
200
        $result = $this->filterTaxableExtensionResults(
201
            $this->extend("updateShowPriceWithTax", $show)
202
        );
203
204
        if (!empty($result)) {
205
            return (bool)$result;
206
        }
207
208
        return (bool)$show;
209
    }
210
211
    /**
212
     * We don't want to show a tax string on Line Items
213
     *
214
     * @return false
215
     */
216
    public function getShowTaxString()
217
    {
218
        return false;
219
    }
220
221
    /**
222
     * Modify default field scaffolding in admin
223
     *
224
     * @return FieldList
225
     */
226
    public function getCMSFields()
227
    {
228
        $this->beforeUpdateCMSFields(function ($fields) {
229
            $config = SiteConfig::current_site_config();
230
231
            $fields->removeByName(
232
                [
233
                    'Customisation',
234
                    'Price',
235
                    'TaxID'
236
                ]
237
            );
238
239
            $fields->addFieldToTab(
240
                "Root.Main",
241
                ReadonlyField::create("Key"),
242
                "Title"
243
            );
244
245
            $fields->addFieldToTab(
246
                "Root.Main",
247
                DropdownField::create(
248
                    "TaxRateID",
249
                    $this->fieldLabel("TaxRate"),
250
                    $config->TaxRates()->map()
251
                ),
252
                "Quantity"
253
            );
254
255
            // Change unlink button to remove on customisation
256
            $custom_field = $fields->dataFieldByName("Customisations");
257
258
            if ($custom_field) {
259
                $config = $custom_field->getConfig();
260
                $config
261
                    ->removeComponentsByType(GridFieldDeleteAction::class)
262
                    ->removeComponentsByType(GridFieldDataColumns::class)
263
                    ->removeComponentsByType(GridFieldEditButton::class)
264
                    ->removeComponentsByType(GridFieldAddNewButton::class)
265
                    ->removeComponentsByType(GridFieldAddExistingAutocompleter::class)
266
                    ->addComponents(
267
                        new GridFieldEditableColumns(),
268
                        new GridFieldAddNewInlineButton(),
269
                        new GridFieldEditButton(),
270
                        new GridFieldDeleteAction()
271
                    );
272
                
273
                    $custom_field->setConfig($config);
274
            }
275
        });
276
277
        return parent::getCMSFields();
278
    }
279
    
280
    /**
281
     * Get the price for a single line item (unit), minus any tax
282
     *
283
     * @return float
284
     */
285
    public function getNoTaxPrice()
286
    {
287
        $price = $this->getBasePrice();
288
289
        foreach ($this->Customisations() as $customisation) {
0 ignored issues
show
Bug introduced by
The method Customisations() does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

289
        foreach ($this->/** @scrutinizer ignore-call */ Customisations() as $customisation) {
Loading history...
290
            $price += $customisation->getBasePrice();
291
        }
292
        
293
        $result = $this->getOwner()->filterTaxableExtensionResults(
0 ignored issues
show
Bug introduced by
The method getOwner() does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

293
        $result = $this->/** @scrutinizer ignore-call */ getOwner()->filterTaxableExtensionResults(
Loading history...
294
            $this->extend("updateNoTaxPrice", $price)
295
        );
296
297
        if (!empty($result)) {
298
            return $result;
299
        }
300
301
        return $price;
302
    }
303
304
    public function getUnitPrice()
305
    {
306
        return $this->getNoTaxPrice();
307
    }
308
309
    /**
310
     * Get the amount of tax for a single unit of this item
311
     *
312
     * **NOTE** Tax is rounded at the single item price to avoid multiplication
313
     * weirdness. For example 49.995 + 20% is 59.994 for one product,
314
     * but 239.976 for 4 (it should be 239.96)
315
     *
316
     * @return float
317
     */
318
    public function getUnitTax()
319
    {
320
        // Calculate and round tax now to try and minimise penny rounding issues
321
        $total = ($this->UnitPrice / 100) * $this->TaxPercentage;
0 ignored issues
show
Bug Best Practice introduced by
The property UnitPrice does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property TaxPercentage does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
322
323
        $this->extend("updateUnitTax", $total);
324
325
        return $total;
326
    }
327
328
    /**
329
     * Overwrite TaxAmount with unit tax
330
     *
331
     * @return float
332
     */
333
    public function getTaxAmount()
334
    {
335
        return $this->UnitTax;
0 ignored issues
show
Bug Best Practice introduced by
The property UnitTax does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
336
    }
337
338
    /**
339
     * Get the total price and tax for a single unit
340
     *
341
     * @return float
342
     */
343
    public function getUnitTotal()
344
    {
345
        $total = $this->UnitPrice + $this->UnitTax;
0 ignored issues
show
Bug Best Practice introduced by
The property UnitTax does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property UnitPrice does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
346
347
        $this->extend("updateUnitTotal", $total);
348
349
        return $total;
350
    }
351
352
    /**
353
     * Get the value of this item, minus any tax
354
     *
355
     * @return float
356
     */
357
    public function getSubTotal()
358
    {
359
        $total = $this->NoTaxPrice * $this->Quantity;
0 ignored issues
show
Bug Best Practice introduced by
The property NoTaxPrice does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property Quantity does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
360
361
        $this->extend("updateSubTotal", $total);
362
363
        return $total;
364
    }
365
366
    /**
367
     * Get the total amount of tax for a single unit of this item
368
     *
369
     * @return float
370
     */
371
    public function getTaxTotal()
372
    {
373
        $total = $this->UnitTax * $this->Quantity;
0 ignored issues
show
Bug Best Practice introduced by
The property UnitTax does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property Quantity does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
374
375
        $this->extend("updateTaxTotal", $total);
376
377
        return $total;
378
    }
379
380
    /**
381
     * Get the value of this item, minus any tax
382
     *
383
     * @return float
384
     */
385
    public function getTotal()
386
    {
387
        $total = $this->SubTotal + $this->TaxTotal;
0 ignored issues
show
Bug Best Practice introduced by
The property SubTotal does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property TaxTotal does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
388
389
        $this->extend("updateTotal", $total);
390
    
391
        return $total;
392
    }
393
394
    /**
395
     * Get an image object associated with this line item.
396
     * By default this is retrieved from the base product.
397
     *
398
     * @return Image | null
0 ignored issues
show
Bug introduced by
The type SilverCommerce\OrdersAdmin\Model\Image was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
399
     */
400
    public function Image()
401
    {
402
        $product = $this->FindStockItem();
403
404
        if ($product && method_exists($product, "SortedImages")) {
405
            return  $product->SortedImages()->first();
406
        } elseif ($product && method_exists($product, "Images")) {
407
            return $product->Images()->first();
408
        } elseif ($product && method_exists($product, "Image") && $product->Image()->exists()) {
409
            return $product->Image();
410
        }
411
    }
412
    
413
    /**
414
     * Provide a string of customisations seperated by a comma but not
415
     * including a price
416
     *
417
     * @return string
418
     */
419
    public function getCustomisationList()
420
    {
421
        $return = [];
422
        $items = $this->Customisations();
423
424
        if ($items && $items->exists()) {
425
            foreach ($items as $item) {
426
                $return[] = $item->Title . ': ' . $item->Value;
427
            }
428
        }
429
430
        $this->extend("updateCustomisationList", $return);
431
432
        return implode(", ", $return);
433
    }
434
435
    /**
436
     * Provide a string of customisations seperated by a comma and
437
     * including a price
438
     *
439
     * @return string
440
     */
441
    public function getCustomisationAndPriceList()
442
    {
443
        $return = [];
444
        $items = $this->Customisations();
445
446
        if ($items && $items->exists()) {
447
            foreach ($items as $item) {
448
                $return[] = $item->Title . ': ' . $item->Value . ' (' . $item->getFormattedPrice() . ')';
449
            }
450
        }
451
452
        $this->extend("updateCustomisationAndPriceList", $return);
453
454
        return implode(", ", $return);
455
    }
456
    
457
    /**
458
     * Get list of customisations rendering into a basic
459
     * HTML string
460
     *
461
     * @return HTMLText
462
     */
463
    public function CustomisationHTML()
464
    {
465
        $return = HTMLText::create();
466
        $items = $this->Customisations();
467
        $html = "";
468
        
469
        if ($items && $items->exists()) {
470
            foreach ($items as $item) {
471
                $html .= $item->Title . ': ' . $item->Value . ";<br/>";
472
            }
473
        }
474
475
        $return->setValue($html);
476
477
        $this->extend("updateCustomisationHTML", $return);
478
479
        return $return;
480
    }
481
        
482
    /**
483
     * Match this item to another object in the Database, by the
484
     * provided details.
485
     *
486
     * @param $relation_name = The class name of the related dataobject
0 ignored issues
show
Documentation Bug introduced by
The doc comment = at position 0 could not be parsed: Unknown type name '=' at position 0 in =.
Loading history...
487
     * @param $relation_col = The column name of the related object
488
     * @param $match_col = The column we use to match the two objects
489
     * @return DataObject
490
     */
491
    public function Match($relation_name = null, $relation_col = "StockID", $match_col = "StockID")
492
    {
493
        // Try to determine relation name
494
        if (!$relation_name && !$this->ProductClass && class_exists(CatalogueProduct::class)) {
0 ignored issues
show
Bug introduced by
The type SilverCommerce\OrdersAdmin\Model\CatalogueProduct was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
Bug Best Practice introduced by
The property ProductClass does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
495
            $relation_name = CatalogueProduct::class;
496
        } elseif (!$relation_name && $this->ProductClass) {
497
            $relation_name = $this->ProductClass;
498
        }
499
500
        // Setup filter and check for existence of subsites
501
        // (as sometimes dubplicate stock ID's are found from another subsite)
502
        $filter = [];
503
        $filter[$relation_col] = $this->{$match_col};
504
505
        $subsites_exists = ModuleLoader::inst()->getManifest()->moduleExists('silverstripe/subsites');
506
        if ($subsites_exists) {
507
            $filter['SubsiteID'] = SubsiteState::singleton()->getSubsiteId();
508
        }
509
510
        return $relation_name::get()
511
            ->filter($filter)
512
            ->first();
513
    }
514
515
    /**
516
     * Find our original stock item (useful for adding links back to the
517
     * original product).
518
     *
519
     * This function is a synonym for @Link Match (as a result of) merging
520
     * LineItem
521
     *
522
     * @return DataObject
523
     */
524
    public function FindStockItem()
525
    {
526
        return $this->Match();
527
    }
528
529
    /**
530
     * Check stock levels for this item, will return the actual number
531
     * of remaining stock after removing the current quantity
532
     *
533
     * @param $qty The quantity we want to check against
0 ignored issues
show
Bug introduced by
The type SilverCommerce\OrdersAdmin\Model\The was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
534
     * @return Int
535
     */
536
    public function checkStockLevel($qty)
537
    {
538
        $stock_param = $this->config()->get("stock_param");
539
        $item = $this->Match();
540
        $stock = ($item->$stock_param) ? $item->$stock_param : 0;
541
        $return = $stock - $qty;
542
543
        $this->extend("updateCheckStockLevel", $return);
544
        
545
        return $return;
546
    }
547
548
    /**
549
     * Generate a key based on this item and its customisations
550
     *
551
     * @return string
552
     */
553
    public function generateKey()
554
    {
555
        // Generate a unique item key based on the current ID and customisations
556
        $key = base64_encode(
557
            json_encode(
558
                $this->Customisations()->map("Title", "Value")->toArray()
559
            )
560
        );
561
        return $this->StockID . ':' . $key;
0 ignored issues
show
Bug Best Practice introduced by
The property StockID does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __get, consider adding a @property annotation.
Loading history...
562
    }
563
564
    /**
565
     * Only order creators or users with VIEW admin rights can view
566
     *
567
     * @return Boolean
568
     */
569
    public function canView($member = null, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed. ( Ignorable by Annotation )

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

569
    public function canView($member = null, /** @scrutinizer ignore-unused */ $context = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
570
    {
571
        $extended = $this->extend('canView', $member);
572
        if ($extended && $extended !== null) {
573
            return $extended;
574
        }
575
576
        return $this->Parent()->canView($member);
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SilverCommerce\OrdersAdmin\Model\LineItem. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

576
        return $this->/** @scrutinizer ignore-call */ Parent()->canView($member);
Loading history...
577
    }
578
579
    /**
580
     * Anyone can create an order item
581
     *
582
     * @return Boolean
583
     */
584
    public function canCreate($member = null, $context = [])
585
    {
586
        $extended = $this->extend('canCreate', $member);
587
        if ($extended && $extended !== null) {
588
            return $extended;
589
        }
590
591
        return true;
592
    }
593
594
    /**
595
     * No one can edit items once they are created
596
     *
597
     * @return Boolean
598
     */
599
    public function canEdit($member = null, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed. ( Ignorable by Annotation )

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

599
    public function canEdit($member = null, /** @scrutinizer ignore-unused */ $context = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
600
    {
601
        $extended = $this->extend('canEdit', $member);
602
        if ($extended && $extended !== null) {
603
            return $extended;
604
        }
605
606
        return $this->Parent()->canEdit($member);
607
    }
608
609
    /**
610
     * No one can delete items once they are created
611
     *
612
     * @return Boolean
613
     */
614
    public function canDelete($member = null, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $context is not used and could be removed. ( Ignorable by Annotation )

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

614
    public function canDelete($member = null, /** @scrutinizer ignore-unused */ $context = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
615
    {
616
        $extended = $this->extend('canDelete', $member);
617
        if ($extended && $extended !== null) {
618
            return $extended;
619
        }
620
621
        return $this->Parent()->canEdit($member);
622
    }
623
624
    /**
625
     * Overwrite default duplicate function
626
     *
627
     * @param boolean $doWrite (write the cloned object to DB)
628
     * @return DataObject $clone The duplicated object
629
     */
630
    public function duplicate($doWrite = true, $manyMany = "many_many")
631
    {
632
        $clone = parent::duplicate($doWrite);
633
634
        // Ensure we clone any customisations
635
        if ($doWrite) {
636
            foreach ($this->Customisations() as $customisation) {
637
                $new_item = $customisation->duplicate(false);
638
                $new_item->ParentID = $clone->ID;
639
                $new_item->write();
640
            }
641
        }
642
643
        return $clone;
644
    }
645
646
    /**
647
     * Pre-write tasks
648
     *
649
     * @return void
650
     */
651
    public function onBeforeWrite()
652
    {
653
        parent::onBeforeWrite();
654
        $this->Key = $this->generateKey();
0 ignored issues
show
Bug Best Practice introduced by
The property Key does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
655
    }
656
657
    /**
658
     * Clean up DB on deletion
659
     *
660
     * @return void
661
     */
662
    public function onBeforeDelete()
663
    {
664
        parent::onBeforeDelete();
665
666
        foreach ($this->Customisations() as $customisation) {
667
            $customisation->delete();
668
        }
669
    }
670
}
671