Passed
Branch develop (e2bf59)
by
unknown
29:11
created

FormResource   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 204
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 93
dl 0
loc 204
rs 6.4799
c 2
b 0
f 0
wmc 54

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
D select_types_resource() 0 62 25
F select_resource_list() 0 81 28

How to fix   Complexity   

Complex Class

Complex classes like FormResource often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormResource, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* Copyright (C) - 2013-2015 Jean-François FERRY	<[email protected]>
3
 * Copyright (C) 2019       Frédéric France         <[email protected]>
4
 * Copyright (C) 2022       Ferran Marcet           <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 * or see https://www.gnu.org/
19
 */
20
21
/**
22
 *       \file       resource/class/html.formresource.class.php
23
 *       \ingroup    core
24
 *       \brief      Class file to manage forms into resource module
25
 */
26
require_once DOL_DOCUMENT_ROOT."/core/class/html.form.class.php";
27
require_once DOL_DOCUMENT_ROOT."/resource/class/dolresource.class.php";
28
29
30
/**
31
 * Class to manage forms for the module resource
32
 *
33
 * \remarks Utilisation: $formresource = new FormResource($db)
34
 * \remarks $formplace->proprietes=1 ou chaine ou tableau de valeurs
35
 */
36
class FormResource
37
{
38
	/**
39
	 * @var DoliDB Database handler.
40
	 */
41
	public $db;
42
43
	public $substit = array();
44
45
	public $param = array();
46
47
	/**
48
	 * @var string Error code (or message)
49
	 */
50
	public $error = '';
51
52
53
	/**
54
	 * Constructor
55
	 *
56
	 * @param DoliDB $db Database handler
57
	 */
58
	public function __construct($db)
59
	{
60
		$this->db = $db;
61
	}
62
63
64
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
65
	/**
66
	 *  Output html form to select a resource
67
	 *
68
	 *	@param	int   	$selected       Preselected resource id
69
	 *	@param  string	$htmlname       Name of field in form
70
	 *  @param  string	$filter         Optionnal filters criteras (example: 's.rowid <> x')
71
	 *	@param	int		$showempty		Add an empty field
72
	 * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
73
	 * 	@param	int		$forcecombo		Force to use combo box
74
	 *  @param	array	$event			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
75
	 *  @param	string	$filterkey		Filter on key value
76
	 *  @param	int		$outputmode		0=HTML select string, 1=Array, 2=without form tag
77
	 *  @param	int		$limit			Limit number of answers
78
	 *  @param	string	$morecss		More css
79
	 * 	@param	bool	$multiple       add [] in the name of element and add 'multiple' attribut
80
	 * 	@return	string					HTML string with
81
	 */
82
	public function select_resource_list($selected = '', $htmlname = 'fk_resource', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $event = array(), $filterkey = '', $outputmode = 0, $limit = 20, $morecss = '', $multiple = false)
83
	{
84
		// phpcs:enable
85
		global $conf, $user, $langs;
86
87
		$out = '';
88
		$outarray = array();
89
90
		$resourcestat = new Dolresource($this->db);
91
92
		$resources_used = $resourcestat->fetchAll('ASC', 't.rowid', $limit, 0, $filter);
93
94
		if (!empty($selected) && !is_array($selected)) {
95
			$selected = array($selected);
96
		}
97
98
		if ($outputmode != 2) {
99
			$out = '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
100
			$out .= '<input type="hidden" name="token" value="'.newToken().'">';
101
		}
102
103
		if ($resourcestat) {
104
			if (!empty($conf->use_javascript_ajax) && !empty($conf->global->RESOURCE_USE_SEARCH_TO_SELECT) && !$forcecombo) {
105
				//$minLength = (is_numeric($conf->global->RESOURCE_USE_SEARCH_TO_SELECT)?$conf->global->RESOURCE_USE_SEARCH_TO_SELECT:2);
106
				$out .= ajax_combobox($htmlname, $event, $conf->global->RESOURCE_USE_SEARCH_TO_SELECT);
107
			} else {
108
				$out .= ajax_combobox($htmlname);
109
			}
110
111
			// Construct $out and $outarray
112
			$out .= '<select id="'.$htmlname.'" class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
113
			if ($showempty) {
114
				$out .= '<option value="-1">&nbsp;</option>'."\n";
115
			}
116
117
			$num = 0;
118
			if (is_array($resourcestat->lines)) {
119
				$num = count($resourcestat->lines);
120
			}
121
122
			//var_dump($resourcestat->lines);
123
			$i = 0;
124
			if ($num) {
125
				while ($i < $num) {
126
					$resourceclass = ucfirst($resourcestat->lines[$i]->element);
127
128
					$label = $resourcestat->lines[$i]->ref ? $resourcestat->lines[$i]->ref : ''.$resourcestat->lines[$i]->label;
129
					if ($resourceclass != 'Dolresource') {
130
						$label .= ' ('.$langs->trans($resourceclass).')';
131
					}
132
133
					// Test if entry is the first element of $selected.
134
					if ((isset($selected[0]) && is_object($selected[0]) && $selected[0]->id == $resourcestat->lines[$i]->id) || ((!isset($selected[0]) || !is_object($selected[0])) && !empty($selected) && in_array($resourcestat->lines[$i]->id, $selected))) {
135
						$out .= '<option value="'.$resourcestat->lines[$i]->id.'" selected>'.$label.'</option>';
136
					} else {
137
						$out .= '<option value="'.$resourcestat->lines[$i]->id.'">'.$label.'</option>';
138
					}
139
140
					array_push($outarray, array('key'=>$resourcestat->lines[$i]->id, 'value'=>$resourcestat->lines[$i]->id, 'label'=>$label));
141
142
					$i++;
143
					if (($i % 10) == 0) {
144
						$out .= "\n";
145
					}
146
				}
147
			}
148
			$out .= '</select>'."\n";
149
150
			if ($outputmode != 2) {
151
				$out .= '<input type="submit" class="button" value="'.$langs->trans("Search").'"> &nbsp; &nbsp; ';
152
153
				$out .= '</form>';
154
			}
155
		} else {
156
			dol_print_error($this->db);
157
		}
158
159
		if ($outputmode && $outputmode != 2) {
160
			return $outarray;
161
		}
162
		return $out;
163
	}
164
165
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
166
	/**
167
	 *  Return html list of tickets type
168
	 *
169
	 *  @param	string	$selected       Id du type pre-selectionne
170
	 *  @param  string	$htmlname       Nom de la zone select
171
	 *  @param  string	$filtertype     To filter on field type in llx_c_ticket_type (array('code'=>xx,'label'=>zz))
172
	 *  @param  int		$format         0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
173
	 *  @param  int		$empty			1=peut etre vide, 0 sinon
174
	 *  @param	int		$noadmininfo	0=Add admin info, 1=Disable admin info
175
	 *  @param  int		$maxlength      Max length of label
176
	 * 	@return	void
177
	 */
178
	public function select_types_resource($selected = '', $htmlname = 'type_resource', $filtertype = '', $format = 0, $empty = 0, $noadmininfo = 0, $maxlength = 0)
179
	{
180
		// phpcs:enable
181
		global $langs, $user;
182
183
		$resourcestat = new Dolresource($this->db);
184
185
		dol_syslog(get_class($this)."::select_types_resource ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
186
187
		$filterarray = array();
188
189
		if ($filtertype != '' && $filtertype != '-1') {
190
			$filterarray = explode(',', $filtertype);
191
		}
192
193
		$resourcestat->load_cache_code_type_resource();
194
		print '<select id="select'.$htmlname.'" class="flat maxwidthonsmartphone select_'.$htmlname.'" name="'.$htmlname.'">';
195
		if ($empty) {
196
			print '<option value="">&nbsp;</option>';
197
		}
198
		if (is_array($resourcestat->cache_code_type_resource) && count($resourcestat->cache_code_type_resource)) {
199
			foreach ($resourcestat->cache_code_type_resource as $id => $arraytypes) {
200
				// We discard empty line if showempty is on because an empty line has already been output.
201
				if ($empty && empty($arraytypes['code'])) {
202
					continue;
203
				}
204
205
				if ($format == 0) {
206
					print '<option value="'.$id.'"';
207
				} elseif ($format == 1) {
208
					print '<option value="'.$arraytypes['code'].'"';
209
				} elseif ($format == 2) {
210
					print '<option value="'.$arraytypes['code'].'"';
211
				} elseif ($format == 3) {
212
					print '<option value="'.$id.'"';
213
				}
214
				// Si selected est text, on compare avec code, sinon avec id
215
				if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
216
					print ' selected';
217
				} elseif ($selected == $id) {
218
					print ' selected';
219
				}
220
				print '>';
221
				if ($format == 0) {
222
					$value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
223
				} elseif ($format == 1) {
224
					$value = $arraytypes['code'];
225
				} elseif ($format == 2) {
226
					$value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
227
				} elseif ($format == 3) {
228
					$value = $arraytypes['code'];
229
				}
230
				if (empty($value)) {
231
					$value = '&nbsp;';
232
				}
233
				print $value;
234
				print '</option>';
235
			}
236
		}
237
		print '</select>';
238
		if ($user->admin && !$noadmininfo) {
239
			print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
240
		}
241
	}
242
}
243