Passed
Pull Request — master (#5)
by Jason
02:06
created

ProductDataExtension   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 46
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getActiveDiscount() 0 22 6
A getDiscountPrice() 0 7 2
1
<?php
2
3
namespace Dynamic\Foxy\Discounts\Extension;
4
5
use Dynamic\Foxy\Discounts\Model\Discount;
6
use SilverStripe\ORM\DataExtension;
7
8
class ProductDataExtension extends DataExtension
9
{
10
    /**
11
     * @var array
12
     */
13
    private static $belongs_many_many = [
0 ignored issues
show
introduced by
The private property $belongs_many_many is not used, and could be removed.
Loading history...
14
        'Discounts' => Discount::class,
15
    ];
16
17
    /**
18
     * @return bool|float|int|mixed
19
     */
20
    public function getDiscountPrice()
21
    {
22
        if ($discount = $this->getActiveDiscount()) {
0 ignored issues
show
Unused Code introduced by
The assignment to $discount is dead and can be removed.
Loading history...
23
            $price = $this->owner->Price - ($this->owner->Price * ($this->getActiveDiscount()->Percentage/100));
24
            return $price;
25
        }
26
        return false;
27
    }
28
29
    /**
30
     * @return mixed
31
     */
32
    public function getActiveDiscount()
33
    {
34
        $filter = [
35
            'StartTime:LessThanOrEqual' => date("Y-m-d H:i:s", strtotime('now')),
36
            'EndTime:GreaterThanOrEqual' => date("Y-m-d H:i:s", strtotime('now')),
37
        ];
38
39
        if ($this->owner->Discounts()->filter($filter)->count() > 0) {
40
            foreach ($this->owner->Discounts()->filter($filter)->sort('Percentage DESC') as $discount) {
41
                if ($discount->getIsActive()) {
42
                    return $discount;
43
                }
44
            }
45
        }
46
47
        foreach (Discount::get()->filter($filter)->sort('Percentage DESC') as $discount) {
48
            if ($discount->getIsGlobal()) {
49
                return $discount;
50
            }
51
        }
52
53
        return false;
54
    }
55
}
56