Completed
Push — master ( 32b4c2...be6d62 )
by Matthew
22:47 queued 07:45
created

PurchaseFormExtension::isOutOfStock()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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