Passed
Push — master ( a7c50c...ab63ad )
by Nic
03:11
created

DiscountTier::onBeforeWrite()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Dynamic\Foxy\Discounts\Model;
4
5
use Dynamic\Foxy\Coupons\Model\Coupon;
0 ignored issues
show
Bug introduced by
The type Dynamic\Foxy\Coupons\Model\Coupon 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...
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\ORM\DataObject;
8
9
/**
10
 * Class DiscountTier
11
 * @package Dynamic\Foxy\Discounts\Model
12
 *
13
 * @property string $ParentType Save the parent Discount's type so we don't need to run a query
14
 * @property int $Quantity
15
 * @property int $Percentage
16
 * @property float $Amount
17
 * @property int $DiscountID
18
 * @method Discount Discount()
19
 */
20
class DiscountTier extends DataObject
21
{
22
    /**
23
     * @var array
24
     */
25
    private static $db = [
26
        'ParentType' => 'Varchar',
27
        'Quantity' => 'Int',
28
        'Percentage' => 'Int',
29
        'Amount' => 'Currency',
30
    ];
31
32
    /**
33
     * @var array
34
     */
35
    private static $has_one = [
36
        'Discount' => Discount::class,
37
    ];
38
39
    /**
40
     * @var array
41
     */
42
    private static $defaults = [
43
        'Quantity' => 1,
44
    ];
45
46
    /**
47
     * @var array
48
     */
49
    private static $summary_fields = [
50
        'DiscountLabel' => [
51
            'title' => 'Discount',
52
        ],
53
        'Quantity',
54
    ];
55
56
    /**
57
     * @var string
58
     */
59
    private static $table_name = 'FoxyDiscountTier';
60
61
    /**
62
     * @var array
63
     */
64
    private static $default_sort = [
65
        'Quantity',
66
    ];
67
68
    /**
69
     * @return FieldList|void
70
     */
71
    public function getCMSFields()
72
    {
73
        $this->beforeUpdateCMSFields(function (FieldList $fields) {
74
            $fields->removeByName([
75
                'DiscountID',
76
            ]);
77
78
            $quantity = $fields->dataFieldByName('Quantity');
79
            $quantity->setTitle('Quantity to trigger discount');
80
81
            /** @var Discount|Coupon $type */
82
            if ($parent = $this->getParent()) {
83
                $type = $parent->Type;
0 ignored issues
show
Bug introduced by
The property Type does not exist on string.
Loading history...
84
85
                $percentage = $fields->dataFieldByName('Percentage')
86
                    ->setTitle('Percent discount');
87
                $amount = $fields->dataFieldByName('Amount')
88
                    ->setTitle('Amount to discount');
89
90
                $fields->removeByName([
91
                    'Percentage',
92
                    'Amount',
93
                ]);
94
95
                if ($type == 'Percent') {
96
                    $fields->addFieldToTab(
97
                        'Root.Main',
98
                        $percentage
99
                    );
100
                } elseif ($type == 'Amount') {
101
                    $fields->addFieldToTab(
102
                        'Root.Main',
103
                        $amount
104
                    );
105
                }
106
            }
107
        });
108
109
        return parent::getCMSFields();
110
    }
111
112
    protected function onBeforeWrite()
113
    {
114
        parent::onBeforeWrite();
115
116
        $this->ParentType = $this->Discount()->Type;
117
    }
118
119
    /**
120
     * @return string
121
     */
122
    protected function getParent()
123
    {
124
        foreach ($this->hasOne() as $relationName => $className) {
125
            $field = "{$relationName}ID";
126
127
            if ($this->{$field} > 0) {
128
                return $className::get()->byID($this->{$field});
129
            }
130
        }
131
132
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
133
    }
134
135
    /**
136
     * @return \SilverStripe\ORM\ValidationResult|void
137
     */
138
    public function validate()
139
    {
140
        $response = parent::validate();
141
142
        if ($this->exists()) {
143
            $exclude['ID'] = $this->ID;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$exclude was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exclude = array(); before regardless.
Loading history...
144
        }
145
146
        /** @var Discount $discount */
147
        if ($discount = Discount::get()->byID($this->DiscountID)) {
148
            $existing = $discount->DiscountTiers()->filter('Quantity', $this->Quantity);
149
            if (isset($exclude)) {
150
                $existing = $existing->exclude($exclude);
151
            }
152
153
            if ($existing->count() > 0) {
154
                $response->addError("A discount tier already has the quantity {$this->Quantity} set");
155
            }
156
        }
157
158
        return $response;
159
    }
160
161
    /**
162
     * @return string
163
     */
164
    public function getDiscountLabel()
165
    {
166
        $label = '';
167
168
        if ($this->ParentType == 'Percent') {
169
            $label = "{$this->Percentage}%";
170
        } elseif ($this->ParentType == 'Amount') {
171
            $label = $this->dbObject('Amount')->Nice();
172
        }
173
174
        $this->extend('updateDiscountLabel', $label);
175
176
        return $label;
177
    }
178
}
179