QuantityFieldExtension::onBeforeRender()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 2
b 0
f 0
nc 3
nop 0
dl 0
loc 13
rs 10
1
<?php
2
3
namespace Dynamic\FoxyStripe\Extension;
4
5
use SilverStripe\Core\Extension;
6
7
/**
8
 * Class QuantityFieldExtension
9
 * @package Dynamic\FoxyStripe\Extension
10
 *
11
 * @property-read \Dynamic\FoxyStripe\Form\QuantityField $owner
12
 */
13
class QuantityFieldExtension extends Extension
14
{
15
16
    public function onBeforeRender()
17
    {
18
        if (!$this->owner->getProduct()->hasMethod('getHasInventory')) {
19
            return;
20
        }
21
22
        if (!$this->owner->getProduct()->getHasInventory()) {
23
            return;
24
        }
25
26
        $this->owner->setAttribute(
27
            'data-limit',
28
            $this->owner->getProduct()->getNumberAvailable()
29
        );
30
    }
31
32
    /**
33
     * Limit the quantity to the number available
34
     * @param $quantity
35
     */
36
    public function updateQuantity(&$quantity)
37
    {
38
        if (!$this->owner->getProduct()->hasMethod('getHasInventory')) {
39
            return;
40
        }
41
42
        if (!$this->owner->getProduct()->getHasInventory()) {
43
            return;
44
        }
45
46
        if ($quantity >= $this->owner->getProduct()->getNumberAvailable()) {
47
            $quantity = $this->owner->getProduct()->getNumberAvailable();
48
        }
49
    }
50
51
    /**
52
     * Adds limit
53
     * @param $data
54
     */
55
    public function updateData(&$data)
56
    {
57
        if (!$this->owner->getProduct()->hasMethod('getHasInventory')) {
58
            return;
59
        }
60
61
        if (!$this->owner->getProduct()->getHasInventory()) {
62
            return;
63
        }
64
65
        $data['limit'] = (int) $this->owner->getProduct()->getNumberAvailable();
66
    }
67
}
68