Passed
Push — main ( d07ee1...38048d )
by Rafael
50:23
created

AdherentTypeController::index()   F

Complexity

Conditions 36
Paths 18027

Size

Total Lines 188
Code Lines 127

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 36
eloc 127
nc 18027
nop 1
dl 0
loc 188
rs 0
c 1
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2001-2002  Rodolphe Quiedeville    <[email protected]>
4
 * Copyright (C) 2003		Jean-Louis Bergamo		<[email protected]>
5
 * Copyright (C) 2004-2011	Laurent Destailleur		<[email protected]>
6
 * Copyright (C) 2005-2017	Regis Houssin			<[email protected]>
7
 * Copyright (C) 2013		Florian Henry			<[email protected]>
8
 * Copyright (C) 2015		Alexandre Spangaro		<[email protected]>
9
 * Copyright (C) 2019-2022	Thibault Foucart		<[email protected]>
10
 * Copyright (C) 2020		Josep Lluís Amador		<[email protected]>
11
 * Copyright (C) 2021		Waël Almoman			<[email protected]>
12
 * Copyright (C) 2024		MDW						<[email protected]>
13
 * Copyright (C) 2024       Rafael San José         <[email protected]>
14
 *
15
 * This program is free software; you can redistribute it and/or modify
16
 * it under the terms of the GNU General Public License as published by
17
 * the Free Software Foundation; either version 3 of the License, or
18
 * (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
27
 */
28
29
namespace DoliModules\Adherent\Controller;
30
31
global $conf;
32
global $db;
33
global $user;
34
global $hookmanager;
35
global $user;
36
global $menumanager;
37
global $langs;
38
global $mysoc;
39
40
// Load Dolibarr environment
41
require_once BASE_PATH . '/main.inc.php';
42
43
use DoliCore\Base\Controller\DolibarrController;
44
use DoliCore\Lib\ExtraFields;
45
use DoliCore\Tools\Load;
46
use DoliModules\Adherent\Model\AdherentType;
47
48
class AdherentTypeController extends DolibarrController
49
{
50
    public $rowid;
51
    public $extrafields;
52
    public $massaction;
53
    public $cancel;
54
    public $toselect;
55
    public $contextpage;
56
    public $backtopage;
57
    public $mode;
58
    public $sall;
59
    public $filter;
60
    public $search_ref;
61
    public $search_lastname;
62
    public $search_login;
63
    public $search_email;
64
    public $type;
65
    public $status;
66
    public $optioncss;
67
    public $limit;
68
    public $sortfield;
69
    public $sortorder;
70
    public $page;
71
    public $pagenext;
72
    public $label;
73
    public $morphy;
74
    public $offset;
75
    public $pageprev;
76
    public $subscription;
77
    public $amount;
78
    public $duration_value;
79
    public $duration_unit;
80
    public $vote;
81
    public $comment;
82
    public $mail_valid;
83
    public $caneditamount;
84
85
    /**
86
     *      \file       htdocs/adherents/type.php
87
     *      \ingroup    member
88
     *      \brief      Member's type setup
89
     */
90
    public function doIndex(): bool
91
    {
92
        global $conf;
93
        global $db;
94
        global $user;
95
        global $hookmanager;
96
        global $user;
97
        global $menumanager;
98
        global $langs;
99
100
        // Load translation files required by the page
101
        $this->langs->load("members");
102
103
        $action = $this->filterPost('action', 'aZ09');
104
        if ($action === 'create') {
105
            $this->template = '/page/adherent/type_edit';
106
            return true;
107
        }
108
109
        if ($action === 'cancel') {
110
            $this->template = '/page/adherent/type_list';
111
            return true;
112
        }
113
114
        /*
115
         *  Actions
116
         */
117
118
        if ($this->filterPost('button_removefilter_x', 'alpha') || $this->filterPost('button_removefilter_x', 'alpha') || $this->filterPost('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
119
            $search_ref = "";
120
            $search_lastname = "";
121
            $search_login = "";
122
            $search_email = "";
123
            $type = "";
124
            $sall = "";
125
        }
126
127
        if ($this->filterPost('cancel', 'alpha')) {
128
            $action = 'list';
129
            $massaction = '';
130
        }
131
132
        if (!$this->filterPost('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
133
            $massaction = '';
134
        }
135
136
        if ($cancel) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $cancel seems to be never defined.
Loading history...
137
            $action = '';
138
139
            if (!empty($backtopage)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $backtopage seems to never exist and therefore empty should always be true.
Loading history...
140
                header("Location: " . $backtopage);
141
                exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
142
            }
143
        }
144
145
        if ($action == 'add' && $user->hasRight('adherent', 'configurer')) {
146
            $this->object->label = trim($label);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $label seems to be never defined.
Loading history...
147
            $this->object->morphy = trim($morphy);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $morphy seems to be never defined.
Loading history...
148
            $this->object->status = (int)$status;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $status seems to be never defined.
Loading history...
149
            $this->object->subscription = (int)$subscription;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $subscription seems to be never defined.
Loading history...
150
            $this->object->amount = ($amount == '' ? '' : price2num($amount, 'MT'));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $amount seems to be never defined.
Loading history...
151
            $this->object->caneditamount = $caneditamount;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $caneditamount seems to be never defined.
Loading history...
152
            $this->object->duration_value = $duration_value;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $duration_value seems to be never defined.
Loading history...
153
            $this->object->duration_unit = $duration_unit;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $duration_unit seems to be never defined.
Loading history...
154
            $this->object->note_public = trim($comment);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $comment seems to be never defined.
Loading history...
155
            $this->object->note_private = '';
156
            $this->object->mail_valid = trim($mail_valid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mail_valid seems to be never defined.
Loading history...
157
            $this->object->vote = (int)$vote;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $vote seems to be never defined.
Loading history...
158
159
            // Fill array 'array_options' with data from add form
160
            $ret = $extrafields->setOptionalsFromPost(null, $this->object);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extrafields seems to be never defined.
Loading history...
161
            if ($ret < 0) {
162
                $error++;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
163
            }
164
165
            if (empty($this->object->label)) {
166
                $error++;
167
                setEventMessages($this->langs->trans("ErrorFieldRequired", $this->langs->transnoentities("Label")), null, 'errors');
168
            } else {
169
                $sql = "SELECT libelle FROM " . MAIN_DB_PREFIX . "adherent_type WHERE libelle = '" . $this->db->escape($this->object->label) . "'";
0 ignored issues
show
Bug introduced by
The method escape() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

169
                $sql = "SELECT libelle FROM " . MAIN_DB_PREFIX . "adherent_type WHERE libelle = '" . $this->db->/** @scrutinizer ignore-call */ escape($this->object->label) . "'";

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
170
                $sql .= " WHERE entity IN (" . getEntity('member_type') . ")";
171
                $result = $this->db->query($sql);
172
                $num = null;
173
                if ($result) {
174
                    $num = $this->db->num_rows($result);
175
                }
176
                if ($num) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $num of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
177
                    $error++;
178
                    $this->langs->load("errors");
179
                    setEventMessages($this->langs->trans("ErrorLabelAlreadyExists", $login), null, 'errors');
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $login seems to be never defined.
Loading history...
180
                }
181
            }
182
183
            if (!$error) {
184
                $id = $this->object->create($user);
185
                if ($id > 0) {
186
                    header("Location: " . $_SERVER['PHP_SELF']);
187
                    exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
188
                } else {
189
                    setEventMessages($this->object->error, $this->object->errors, 'errors');
190
                    $action = 'create';
191
                }
192
            } else {
193
                $action = 'create';
194
            }
195
        }
196
197
        if ($action == 'update' && $user->hasRight('adherent', 'configurer')) {
198
            $this->object->fetch($this->rowid);
199
200
            $this->object->oldcopy = dol_clone($this->object, 2);
201
202
            $this->object->label = trim($label);
203
            $this->object->morphy = trim($morphy);
204
            $this->object->status = (int)$status;
205
            $this->object->subscription = (int)$subscription;
206
            $this->object->amount = ($amount == '' ? '' : price2num($amount, 'MT'));
207
            $this->object->caneditamount = $caneditamount;
208
            $this->object->duration_value = $duration_value;
209
            $this->object->duration_unit = $duration_unit;
210
            $this->object->note_public = trim($comment);
211
            $this->object->note_private = '';
212
            $this->object->mail_valid = trim($mail_valid);
213
            $this->object->vote = (bool)trim($vote);
214
215
            // Fill array 'array_options' with data from add form
216
            $ret = $extrafields->setOptionalsFromPost(null, $this->object, '@GETPOSTISSET');
217
            if ($ret < 0) {
218
                $error++;
219
            }
220
221
            $ret = $this->object->update($user);
222
223
            if ($ret >= 0 && !count($this->object->errors)) {
224
                setEventMessages($this->langs->trans("MemberTypeModified"), null, 'mesgs');
225
            } else {
226
                setEventMessages($this->object->error, $this->object->errors, 'errors');
227
            }
228
229
            header("Location: " . $_SERVER['PHP_SELF'] . "?rowid=" . $this->object->id);
230
            exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
231
        }
232
233
        if ($action == 'confirm_delete' && $user->hasRight('adherent', 'configurer')) {
234
            $this->object->fetch($this->rowid);
235
            $res = $this->object->delete($user);
236
237
            if ($res > 0) {
238
                setEventMessages($this->langs->trans("MemberTypeDeleted"), null, 'mesgs');
239
                header("Location: " . $_SERVER['PHP_SELF']);
240
                exit;
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
241
            } else {
242
                setEventMessages($this->langs->trans("MemberTypeCanNotBeDeleted"), null, 'errors');
243
                $action = '';
244
            }
245
        }
246
247
        $this->db->close();
248
249
        $this->template = '/page/adherent/type_list';
250
        if ($this->rowid) {
251
            if ($_GET['action'] === 'edit') {
252
                $this->template = '/page/adherent/type_edit';
253
            } else {
254
                $this->template = '/page/adherent/type_show';
255
            }
256
        }
257
258
259
        $this->menu = [];
260
        foreach ($menu as $item) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $menu seems to be never defined.
Loading history...
261
            if ($item['type'] === 'left' || !$item['enabled']) {
262
                continue;
263
            }
264
            $this->menu[] = [
265
                'name' => $item['mainmenu'],
266
                'href' => BASE_URL . $item['url'],
267
                'prefix' => $item['prefix'],
268
                'title' => $item['titre'],
269
                'selected' => false,
270
            ];
271
        }
272
273
        return true;
274
    }
275
276
    public function loadRecord()
277
    {
278
        // Initialize technical objects
279
        $this->object = new AdherentType($this->db);
280
        $this->extrafields = new ExtraFields($this->db);
281
        $this->hookmanager->initHooks(['membertypecard', 'globalcard']);
0 ignored issues
show
Bug introduced by
The method initHooks() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

281
        $this->hookmanager->/** @scrutinizer ignore-call */ 
282
                            initHooks(['membertypecard', 'globalcard']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
282
283
        // Fetch optionals attributes and labels
284
        $this->extrafields->fetch_name_optionals_label($this->object->table_element);
285
286
        $this->rowid = $this->filterPostInt('rowid');
287
        if ($this->rowid) {
288
            $this->object->fetch($this->rowid);
289
        }
290
291
        return true;
292
    }
293
294
    public function loadPost()
295
    {
296
        $this->massaction = $this->filterPost('massaction', 'alpha');
297
        $this->cancel = $this->filterPost('cancel', 'alpha');
298
        $this->toselect = $this->filterPost('toselect', 'array');
299
        $this->contextpage = $this->filterPost('contextpage', 'aZ') ? $this->filterPost('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)) . basename(__FILE__, '.php')); // To manage different context of search
300
        $this->backtopage = $this->filterPost('backtopage', 'alpha');
301
        $this->mode = $this->filterPost('mode', 'alpha');
302
303
        $this->sall = $this->filterPost("sall", "alpha");
304
        $this->filter = $this->filterPost("filter", 'alpha');
305
        $this->search_ref = $this->filterPost('search_ref', 'alpha');
306
        $this->search_lastname = $this->filterPost('search_lastname', 'alpha');
307
        $this->search_login = $this->filterPost('search_login', 'alpha');
308
        $this->search_email = $this->filterPost('search_email', 'alpha');
309
        $this->type = $this->filterPost('type', 'intcomma');
310
        $this->status = $this->filterPost('status', 'alpha');
311
        $this->optioncss = $this->filterPost('optioncss', 'alpha');
312
313
        // Load variable for pagination (move to trait? Create a class? A component?)
314
        $this->limit = $this->filterPostInt('limit') ? $this->filterPostInt('limit') : $this->conf->liste_limit;
315
        $this->sortfield = $this->filterPost('sortfield', 'aZ09comma');
316
        $this->sortorder = $this->filterPost('sortorder', 'aZ09comma');
317
        $this->page = GETPOSTISSET('pageplusone') ? ($this->filterPostInt('pageplusone') - 1) : $this->filterPostInt("page");
318
        if (empty($this->page) || $this->page < 0 || $this->filterPost('button_search', 'alpha') || $this->filterPost('button_removefilter', 'alpha')) {
319
            // If $this->page is not defined, or '' or -1 or if we click on clear filters
320
            $this->page = 0;
321
        }
322
        $this->offset = $this->limit * $this->page;
323
        $this->pageprev = $this->page - 1;
324
        $this->pagenext = $this->page + 1;
325
        if (!$this->sortorder) {
326
            $this->sortorder = "DESC";
327
        }
328
        if (!$this->sortfield) {
329
            $this->sortfield = "d.lastname";
330
        }
331
332
        $this->label = $this->filterPost("label", "alpha");
333
        $this->morphy = $this->filterPost("morphy", "alpha");
334
        $this->status = $this->filterPostInt("status");
335
        $this->subscription = $this->filterPostInt("subscription");
336
        $this->amount = $this->filterPost('amount', 'alpha');
337
        $this->duration_value = $this->filterPostInt('duration_value');
338
        $this->duration_unit = $this->filterPost('duration_unit', 'alpha');
339
        $this->vote = $this->filterPostInt("vote");
340
        $this->comment = $this->filterPost("comment", 'restricthtml');
341
        $this->mail_valid = $this->filterPost("mail_valid", 'restricthtml');
342
        $this->caneditamount = $this->filterPostInt("caneditamount");
343
344
        return true;
345
    }
346
}
347