Passed
Pull Request — master (#7)
by Jason
01:54
created

AddToCartFormExtension::updateProductActions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Dynamic\Foxy\Inventory\Extension;
4
5
use Dynamic\Foxy\Form\AddToCartForm;
6
use Dynamic\Foxy\Inventory\Model\CartReservation;
7
use Dynamic\Foxy\Model\FoxyHelper;
8
use SilverStripe\Core\Extension;
9
use SilverStripe\Forms\FieldList;
10
use SilverStripe\Forms\HeaderField;
11
use SilverStripe\Forms\HiddenField;
12
13
class AddToCartFormExtension extends Extension
14
{
15
    /**
16
     * @param \SilverStripe\Forms\FieldList $fields
17
     */
18
    public function updateProductFields(FieldList &$fields)
19
    {
20
        if ($this->owner->getProduct()->CartExpiration) {
21
            $fields->insertAfter(
22
                'weight',
23
                HiddenField::create('expires')
24
                    ->setValue(
25
                        AddToCartForm::getGeneratedValue(
26
                            $this->owner->getProduct()->Code,
27
                            'expires',
28
                            $this->owner->getProduct()->ExpirationMinutes,
29
                            'value'
30
                        )
31
                    )
32
            );
33
        }
34
35
        if ($this->isOutOfStock()) {
36
            $fields = FieldList::create(
37
                HeaderField::create('OutOfStock', 'Out of stock')
38
                    ->setHeadingLevel(3)
39
            );
40
        }
41
    }
42
43
    /**
44
     * @param \SilverStripe\Forms\FieldList $actions
45
     */
46
    public function updateProductActions(FieldList &$actions)
47
    {
48
        if ($this->isOutOfStock()) {
49
            $actions = FieldList::create();
50
        }
51
    }
52
53
    /**
54
     * @return bool
55
     */
56
    public function isOutOfStock()
57
    {
58
        if (!$this->owner->getProduct()->ControlInventory) {
59
            return false;
60
        }
61
        $reserved = CartReservation::get()
62
            ->filter([
63
                'Code' => $this->owner->getProduct()->Code,
64
                'Expires:GreaterThan' => date('Y-m-d H:i:s', strtotime('now')),
65
            ])->count();
66
        $sold = $this->owner->getProduct()->getNumberPurchased();
67
68
        if ($reserved + $sold >= $this->owner->getProduct()->PurchaseLimit) {
69
            return true;
70
        }
71
72
        return false;
73
    }
74
}
75