Completed
Push — master ( c89319...00e32a )
by Bram
02:25
created

TicketsField::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
1
<?php
2
/**
3
 * TicketsField.php
4
 *
5
 * @author Bram de Leeuw
6
 * Date: 10/03/17
7
 */
8
9
namespace Broarm\EventTickets;
10
11
use ArrayList;
12
use DataList;
13
use DBField;
14
use DropdownField;
15
use FormField;
16
use NumericField;
17
use Validator;
18
19
/**
20
 * Class TicketsField
21
 *
22
 * @package Broarm\EventTickets
23
 */
24
class TicketsField extends FormField
25
{
26
27
    protected $tickets;
28
29
    protected $template = 'TicketsField';
30
31
    public function __construct($name, $title, DataList $tickets)
32
    {
33
        $this->tickets = $tickets;
34
        parent::__construct($name, $title);
35
    }
36
37
    /**
38
     * Set the ticket list
39
     *
40
     * @param DataList $tickets
41
     */
42
    public function setTickets(DataList $tickets)
43
    {
44
        $this->tickets = $tickets;
45
    }
46
47
    /**
48
     * Get the ticket list
49
     *
50
     * @return DataList
51
     */
52
    public function getTickets()
53
    {
54
        return $this->tickets;
55
    }
56
57
    /**
58
     * Get a list of editable tickets
59
     * These have an numeric input field
60
     *
61
     * @return ArrayList
62
     */
63
    private function getEditableTickets()
64
    {
65
        $tickets = ArrayList::create();
66
        foreach ($this->getTickets() as $ticket) {
67
            /** @var Ticket $ticket */
68
            $fieldName = $this->name . "[{$ticket->ID}][Amount]";
69
            $range = range($ticket->Event()->OrderMin, $ticket->Event()->OrderMax);
0 ignored issues
show
Documentation Bug introduced by
The method Event does not exist on object<Broarm\EventTickets\Ticket>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
70
71
            $ticket->AmountField = DropdownField::create(
72
                $fieldName,
73
                'Amount',
74
                array_combine($range, $range),
75
                $ticket->Event()->OrderMin
0 ignored issues
show
Documentation Bug introduced by
The method Event does not exist on object<Broarm\EventTickets\Ticket>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
76
            );
77
78
            $availability = $ticket->Event()->getAvailability();
0 ignored issues
show
Documentation Bug introduced by
The method Event does not exist on object<Broarm\EventTickets\Ticket>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
79
            if ($availability < $ticket->Event()->OrderMax) {
0 ignored issues
show
Documentation Bug introduced by
The method Event does not exist on object<Broarm\EventTickets\Ticket>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
80
                $disabled = range($availability + 1, $ticket->Event()->OrderMax);
0 ignored issues
show
Documentation Bug introduced by
The method Event does not exist on object<Broarm\EventTickets\Ticket>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
81
                $ticket->AmountField->setDisabledItems(array_combine($disabled, $disabled));
82
            }
83
84
            if (!$ticket->getAvailable()) {
85
                $ticket->AmountField->setDisabled(true);
86
            }
87
88
            $tickets->push($ticket);
89
        }
90
        return $tickets;
91
    }
92
93
    /**
94
     * Get the field customized with tickets and reservation
95
     *
96
     * @param array $properties
97
     *
98
     * @return \HTMLText|string
99
     */
100
    public function Field($properties = array())
101
    {
102
        $context = $this;
103
        $properties['Tickets'] = $this->getEditableTickets();
104
105
        if (count($properties)) {
106
            $context = $context->customise($properties);
107
        }
108
109
        $this->extend('onBeforeRender', $this);
110
111
        $result = $context->renderWith($this->getTemplates());
112
113 View Code Duplication
        if (is_string($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
114
            $result = trim($result);
115
        } else {
116
            if ($result instanceof DBField) {
117
                $result->setValue(trim($result->getValue()));
118
            }
119
        }
120
121
        return $result;
122
    }
123
124
    /**
125
     * Make sure a ticket is selected and that the selected amount is available
126
     *
127
     * @param Validator $validator
128
     *
129
     * @return bool
130
     */
131
    public function validate($validator)
132
    {
133
        // Throw an error when there are no tickets selected
134
        if (empty($this->value)) {
135
            $validator->validationError($this->name, _t(
136
                'TicketsField.VALIDATION_EMPTY',
137
                'Select at least one ticket'
138
            ), 'validation');
139
140
            return false;
141
        }
142
143
        // Get the availability
144
        $available = $this->getForm()->event->getAvailability();
145
        // get the sum of selected tickets
146
        $ticketCount = array_sum(array_map(function ($item) {
147
            return $item['Amount'];
148
        }, $this->value));
149
150
        // If the sum of tickets is 0 trow the same error as empty
151
        if ($ticketCount === 0) {
152
            $validator->validationError($this->name, _t(
153
                'TicketsField.VALIDATION_EMPTY',
154
                'Select at least one ticket'
155
            ), 'validation');
156
157
            return false;
158
        }
159
160
        // Throw an error when there are more tickets selected than available
161
        if ($ticketCount > $available) {
162
            $validator->validationError($this->name, _t(
163
                'TicketsField.VALIDATION_TO_MUCH',
164
                'There are {ticketCount} tickets left',
165
                null,
166
                array(
0 ignored issues
show
Documentation introduced by
array('ticketCount' => $available) is of type array<string,?,{"ticketCount":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
167
                    'ticketCount' => $available
168
                )
169
            ), 'validation');
170
171
            return false;
172
        }
173
174
        return false;
175
    }
176
}