TicketsField   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 155
Duplicated Lines 4.52 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 7
dl 7
loc 155
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setTickets() 0 4 1
A getTickets() 0 4 1
A getEditableTickets() 0 31 5
A Field() 7 23 4
A validate() 0 45 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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->OrderMin, $ticket->OrderMax);
70
71
            $ticket->AmountField = DropdownField::create($fieldName, 'Amount', array_combine($range, $range))
72
                ->setHasEmptyDefault(true)
73
                ->setEmptyString(_t('TicketsField.EMPTY', 'Tickets'));
74
75
            // Set the first to hold the minimum
76
            if ($this->getTickets()->count() === 1) {
77
                $ticket->AmountField->setValue($ticket->OrderMin);
78
            }
79
80
            $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...
81
            if ($availability < $ticket->OrderMax) {
82
                $disabled = range($availability + 1, $ticket->OrderMax);
83
                $ticket->AmountField->setDisabledItems(array_combine($disabled, $disabled));
84
            }
85
86
            if (!$ticket->getAvailable()) {
87
                $ticket->AmountField->setDisabled(true);
88
            }
89
90
            $tickets->push($ticket);
91
        }
92
        return $tickets;
93
    }
94
95
    /**
96
     * Get the field customized with tickets and reservation
97
     *
98
     * @param array $properties
99
     *
100
     * @return \HTMLText|string
101
     */
102
    public function Field($properties = array())
103
    {
104
        $context = $this;
105
        $properties['Tickets'] = $this->getEditableTickets();
106
107
        if (count($properties)) {
108
            $context = $context->customise($properties);
109
        }
110
111
        $this->extend('onBeforeRender', $this);
112
113
        $result = $context->renderWith($this->getTemplates());
114
115 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...
116
            $result = trim($result);
117
        } else {
118
            if ($result instanceof DBField) {
119
                $result->setValue(trim($result->getValue()));
120
            }
121
        }
122
123
        return $result;
124
    }
125
126
    /**
127
     * Make sure a ticket is selected and that the selected amount is available
128
     *
129
     * @param Validator $validator
130
     *
131
     * @return bool
132
     */
133
    public function validate($validator)
134
    {
135
        // Throw an error when there are no tickets selected
136
        if (empty($this->value)) {
137
            $validator->validationError($this->name, _t(
138
                'TicketsField.VALIDATION_EMPTY',
139
                'Select at least one ticket'
140
            ), 'validation');
141
142
            return false;
143
        }
144
145
        // Get the availability
146
        $available = $this->getForm()->event->getAvailability();
147
        // get the sum of selected tickets
148
        $ticketCount = array_sum(array_map(function ($item) {
149
            return $item['Amount'];
150
        }, $this->value));
151
152
        // If the sum of tickets is 0 trow the same error as empty
153
        if ($ticketCount === 0) {
154
            $validator->validationError($this->name, _t(
155
                'TicketsField.VALIDATION_EMPTY',
156
                'Select at least one ticket'
157
            ), 'validation');
158
159
            return false;
160
        }
161
162
        // Throw an error when there are more tickets selected than available
163
        if ($ticketCount > $available) {
164
            $validator->validationError($this->name, _t(
165
                'TicketsField.VALIDATION_TO_MUCH',
166
                'There are {ticketCount} tickets left',
167
                null,
168
                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...
169
                    'ticketCount' => $available
170
                )
171
            ), 'validation');
172
173
            return false;
174
        }
175
176
        return false;
177
    }
178
}