Test Failed
Push — main ( 8a0749...ac1aa2 )
by Rafael
44:34
created

AdherentTypeController::index()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 220
Code Lines 150

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 37
eloc 150
c 1
b 0
f 0
nc 481792
nop 1
dl 0
loc 220
rs 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
41
// Load Dolibarr environment
42
require BASE_PATH . '/main.inc.php';
43
44
use DoliCore\Base\DolibarrController;
45
use DoliModules\Adherent\Model\AdherentType;
46
use ExtraFields;
47
48
class AdherentTypeController extends DolibarrController
49
{
50
    /**
51
     *      \file       htdocs/adherents/type.php
52
     *      \ingroup    member
53
     *      \brief      Member's type setup
54
     */
55
    public function index($executeActions = true): bool
56
    {
57
        global $conf;
58
        global $db;
59
        global $user;
60
        global $hookmanager;
61
        global $user;
62
        global $menumanager;
63
        global $langs;
64
        global $mysoc;
65
66
        // Load translation files required by the page
67
        $this->langs->load("members");
68
69
        $rowid = GETPOSTINT('rowid');
70
        $action = GETPOST('action', 'aZ09');
71
        $massaction = GETPOST('massaction', 'alpha');
72
        $cancel = GETPOST('cancel', 'alpha');
73
        $toselect = GETPOST('toselect', 'array');
74
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)) . basename(__FILE__, '.php')); // To manage different context of search
75
        $backtopage = GETPOST('backtopage', 'alpha');
76
        $mode = GETPOST('mode', 'alpha');
77
78
        $sall = GETPOST("sall", "alpha");
79
        $filter = GETPOST("filter", 'alpha');
80
        $search_ref = GETPOST('search_ref', 'alpha');
81
        $search_lastname = GETPOST('search_lastname', 'alpha');
82
        $search_login = GETPOST('search_login', 'alpha');
83
        $search_email = GETPOST('search_email', 'alpha');
84
        $type = GETPOST('type', 'intcomma');
85
        $status = GETPOST('status', 'alpha');
86
        $optioncss = GETPOST('optioncss', 'alpha');
87
88
        // Load variable for pagination
89
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
90
        $sortfield = GETPOST('sortfield', 'aZ09comma');
91
        $sortorder = GETPOST('sortorder', 'aZ09comma');
92
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
93
        if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
94
            // If $page is not defined, or '' or -1 or if we click on clear filters
95
            $page = 0;
96
        }
97
        $offset = $limit * $page;
98
        $pageprev = $page - 1;
99
        $pagenext = $page + 1;
100
        if (!$sortorder) {
101
            $sortorder = "DESC";
102
        }
103
        if (!$sortfield) {
104
            $sortfield = "d.lastname";
105
        }
106
107
        $label = GETPOST("label", "alpha");
108
        $morphy = GETPOST("morphy", "alpha");
109
        $status = GETPOSTINT("status");
110
        $subscription = GETPOSTINT("subscription");
111
        $amount = GETPOST('amount', 'alpha');
112
        $duration_value = GETPOSTINT('duration_value');
113
        $duration_unit = GETPOST('duration_unit', 'alpha');
114
        $vote = GETPOSTINT("vote");
115
        $comment = GETPOST("comment", 'restricthtml');
116
        $mail_valid = GETPOST("mail_valid", 'restricthtml');
117
        $caneditamount = GETPOSTINT("caneditamount");
118
119
        // Initialize technical objects
120
        $object = new AdherentType($db);
121
        $extrafields = new ExtraFields($db);
122
        $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

122
        $this->hookmanager->/** @scrutinizer ignore-call */ 
123
                            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...
123
124
        // Fetch optionals attributes and labels
125
        $extrafields->fetch_name_optionals_label($object->table_element);
126
127
        // Security check
128
        $result = restrictedArea($user, 'adherent', $rowid, 'adherent_type');
129
130
131
        /*
132
         *  Actions
133
         */
134
135
        if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
136
            $search_ref = "";
137
            $search_lastname = "";
138
            $search_login = "";
139
            $search_email = "";
140
            $type = "";
141
            $sall = "";
142
        }
143
144
        if (GETPOST('cancel', 'alpha')) {
145
            $action = 'list';
146
            $massaction = '';
147
        }
148
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
149
            $massaction = '';
150
        }
151
152
        if ($cancel) {
153
            $action = '';
154
155
            if (!empty($backtopage)) {
156
                header("Location: " . $backtopage);
157
                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...
158
            }
159
        }
160
161
        if ($action == 'add' && $user->hasRight('adherent', 'configurer')) {
162
            $object->label = trim($label);
163
            $object->morphy = trim($morphy);
164
            $object->status = (int) $status;
165
            $object->subscription = (int) $subscription;
166
            $object->amount = ($amount == '' ? '' : price2num($amount, 'MT'));
167
            $object->caneditamount = $caneditamount;
168
            $object->duration_value = $duration_value;
169
            $object->duration_unit = $duration_unit;
170
            $object->note_public = trim($comment);
171
            $object->note_private = '';
172
            $object->mail_valid = trim($mail_valid);
173
            $object->vote = (int) $vote;
174
175
            // Fill array 'array_options' with data from add form
176
            $ret = $extrafields->setOptionalsFromPost(null, $object);
177
            if ($ret < 0) {
178
                $error++;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
179
            }
180
181
            if (empty($object->label)) {
182
                $error++;
183
                setEventMessages($this->langs->trans("ErrorFieldRequired", $this->langs->transnoentities("Label")), null, 'errors');
184
            } else {
185
                $sql = "SELECT libelle FROM " . MAIN_DB_PREFIX . "adherent_type WHERE libelle = '" . $this->db->escape($object->label) . "'";
186
                $sql .= " WHERE entity IN (" . getEntity('member_type') . ")";
187
                $result = $this->db->query($sql);
188
                $num = null;
189
                if ($result) {
190
                    $num = $this->db->num_rows($result);
191
                }
192
                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...
193
                    $error++;
194
                    $this->langs->load("errors");
195
                    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...
196
                }
197
            }
198
199
            if (!$error) {
200
                $id = $object->create($user);
201
                if ($id > 0) {
202
                    header("Location: " . $_SERVER['PHP_SELF']);
203
                    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...
204
                } else {
205
                    setEventMessages($object->error, $object->errors, 'errors');
206
                    $action = 'create';
207
                }
208
            } else {
209
                $action = 'create';
210
            }
211
        }
212
213
        if ($action == 'update' && $user->hasRight('adherent', 'configurer')) {
214
            $object->fetch($rowid);
215
216
            $object->oldcopy = dol_clone($object, 2);
217
218
            $object->label = trim($label);
219
            $object->morphy = trim($morphy);
220
            $object->status = (int) $status;
221
            $object->subscription = (int) $subscription;
222
            $object->amount = ($amount == '' ? '' : price2num($amount, 'MT'));
223
            $object->caneditamount = $caneditamount;
224
            $object->duration_value = $duration_value;
225
            $object->duration_unit = $duration_unit;
226
            $object->note_public = trim($comment);
227
            $object->note_private = '';
228
            $object->mail_valid = trim($mail_valid);
229
            $object->vote = (bool) trim($vote);
230
231
            // Fill array 'array_options' with data from add form
232
            $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET');
233
            if ($ret < 0) {
234
                $error++;
235
            }
236
237
            $ret = $object->update($user);
238
239
            if ($ret >= 0 && !count($object->errors)) {
240
                setEventMessages($this->langs->trans("MemberTypeModified"), null, 'mesgs');
241
            } else {
242
                setEventMessages($object->error, $object->errors, 'errors');
243
            }
244
245
            header("Location: " . $_SERVER['PHP_SELF'] . "?rowid=" . $object->id);
246
            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...
247
        }
248
249
        if ($action == 'confirm_delete' && $user->hasRight('adherent', 'configurer')) {
250
            $object->fetch($rowid);
251
            $res = $object->delete($user);
252
253
            if ($res > 0) {
254
                setEventMessages($this->langs->trans("MemberTypeDeleted"), null, 'mesgs');
255
                header("Location: " . $_SERVER['PHP_SELF']);
256
                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...
257
            } else {
258
                setEventMessages($this->langs->trans("MemberTypeCanNotBeDeleted"), null, 'errors');
259
                $action = '';
260
            }
261
        }
262
263
264
        /*
265
         * View
266
         */
267
268
        // require_once realpath(BASE_PATH . '/../Dolibarr/Modules/Adherent/Views/type.php');
269
270
        $this->db->close();
271
272
        $this->template = '/page/adherent/type_list';
273
274
        return true;
275
    }
276
}
277