Completed
Branch develop (bccfa3)
by
unknown
31:46
created

FormAccounting::select_journal()   C

Complexity

Conditions 10
Paths 4

Size

Total Lines 67
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 37
nc 4
nop 9
dl 0
loc 67
rs 6.1506
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) 2016 		Alexandre Spangaro <[email protected]>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16
 */
17
18
/**
19
 *	\file       htdocs/core/class/html.formaccounting.class.php
20
 *  \ingroup    Advanced accountancy
21
 *	\brief      File of class with all html predefined components
22
 */
23
24
25
/**
26
 *	Class to manage generation of HTML components for accounting management
27
 */
28
class FormAccounting extends Form
29
{
30
31
    private $options_cache = array();
32
33
	var $db;
34
	var $error;
35
36
	/**
37
	* Constructor
38
	*
39
	* @param		DoliDB		$db      Database handler
40
	*/
41
	public function __construct($db)
42
	{
43
	    $this->db = $db;
44
	}
45
46
	/**
47
	 * Return list of journals with label by nature
48
	 *
49
	 * @param	string	$selectid	Preselected pcg_type
50
	 * @param	string	$htmlname	Name of field in html form
51
	 * @param	int		$nature		Limit the list to a particular type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
52
	 * @param	int		$showempty	Add an empty field
53
	 * @param	array	$event		Event options
54
	 * @param	int		$select_in	0=selectid value is the journal rowid (default) or 1=selectid is journal code
55
	 * @param	int		$select_out	Set value returned by select. 0=rowid (default), 1=code
56
	 * @param	string	$morecss	More css non HTML object
57
	 * @param	string	$usecache	Key to use to store result into a cache. Next call with same key will reuse the cache.
58
	 *
59
	 * @return	string				String with HTML select
60
	 */
61
	function select_journal($selectid, $htmlname = 'journal', $nature=0, $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
62
	{
63
		global $conf;
64
65
		$out = '';
66
67
    	$options = array();
68
		if ($usecache && ! empty($this->options_cache[$usecache]))
69
		{
70
		    $options = $this->options_cache[$usecache];
71
		    $selected=$selectid;
72
		}
73
		else
74
		{
75
			$sql = "SELECT rowid, code, label, nature, entity, active";
76
			$sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
77
			$sql.= " WHERE active = 1";
78
			$sql.= " AND entity = ".$conf->entity;
79
			//if ($nature && is_numeric($nature))   $sql .= " AND nature = ".$nature;
80
			$sql.= " ORDER BY code";
81
82
			dol_syslog(get_class($this) . "::select_journal", LOG_DEBUG);
83
			$resql = $this->db->query($sql);
84
85
			if (!$resql) {
86
				$this->error = "Error ".$this->db->lasterror();
87
				dol_syslog(get_class($this)."::select_journal ".$this->error, LOG_ERR);
88
				return -1;
89
			}
90
91
			$out = ajax_combobox($htmlname, $event);
92
93
    		$selected = 0;
94
			while ($obj = $this->db->fetch_object($resql))
95
			{
96
				$label = $obj->code . ' - ' . $obj->label;
97
98
    			$select_value_in = $obj->rowid;
99
				$select_value_out = $obj->rowid;
100
101
				// Try to guess if we have found default value
102
    			if ($select_in == 1) {
103
    				$select_value_in = $obj->code;
104
    			}
105
    			if ($select_out == 1) {
106
    				$select_value_out = $obj->code;
107
    			}
108
    			// Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid
109
    			if ($selectid != '' && $selectid == $select_value_in) {
110
    			    //var_dump("Found ".$selectid." ".$select_value_in);
111
    				$selected = $select_value_out;
112
    			}
113
114
				$options[$select_value_out] = $label;
115
			}
116
			$this->db->free($resql);
117
118
			if ($usecache)
119
			{
120
				$this->options_cache[$usecache] = $options;
121
			}
122
		}
123
124
		$out .= Form::selectarray($htmlname, $options, $select, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1);
0 ignored issues
show
Bug introduced by
The variable $select does not exist. Did you mean $selectid?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
125
126
		return $out;
127
	}
128
129
    /**
130
     *	Return list of accounting category.
131
     * 	Use mysoc->country_id or mysoc->country_code so they must be defined.
132
     *
133
     *	@param	string	$selected       Preselected type
134
     *	@param  string	$htmlname       Name of field in form
135
     * 	@param	int		$useempty		Set to 1 if we want an empty value
136
     * 	@param	int		$maxlen			Max length of text in combo box
137
     * 	@param	int		$help			Add or not the admin help picto
138
     *  @param  int     $allcountries   All countries
139
     * 	@return	void
140
     */
141
    function select_accounting_category($selected='',$htmlname='account_category', $useempty=0, $maxlen=0, $help=1, $allcountries=0)
142
    {
143
        global $db,$langs,$user,$mysoc;
144
145
        if (empty($mysoc->country_id) && empty($mysoc->country_code) && empty($allcountries))
146
        {
147
            dol_print_error('','Call to select_accounting_account with mysoc country not yet defined');
148
            exit;
149
        }
150
151
        if (! empty($mysoc->country_id))
152
        {
153
            $sql = "SELECT c.rowid, c.label as type, c.range_account";
154
            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
155
            $sql.= " WHERE c.active = 1";
156
			$sql.= " AND c.category_type = 0";
157
            if (empty($allcountries)) $sql.= " AND c.fk_country = ".$mysoc->country_id;
158
            $sql.= " ORDER BY c.label ASC";
159
        }
160
        else
161
        {
162
            $sql = "SELECT c.rowid, c.label as type, c.range_account";
163
            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
164
            $sql.= " WHERE c.active = 1";
165
			$sql.= " AND c.category_type = 0";
166
			$sql.= " AND c.fk_country = co.rowid";
167
            if (empty($allcountries)) $sql.= " AND co.code = '".$mysoc->country_code."'";
168
            $sql.= " ORDER BY c.label ASC";
169
        }
170
171
        dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
172
        $resql=$db->query($sql);
173
        if ($resql)
174
        {
175
            $num = $db->num_rows($resql);
176
            if ($num)
177
            {
178
                $out = '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'">';
179
                $i = 0;
180
181
                if ($useempty) $out.= '<option value="0">&nbsp;</option>';
182
                while ($i < $num)
183
                {
184
                    $obj = $db->fetch_object($resql);
185
                    $out .= '<option value="'.$obj->rowid.'"';
186
                    if ($obj->rowid == $selected) $out .= ' selected';
187
                    $out .= '>'.($maxlen ? dol_trunc($obj->type,$maxlen) : $obj->type);
188
					$out .= ' ('.$obj->range_account.')';
189
                    $i++;
190
                }
191
                $out .=  '</select>';
192
                //if ($user->admin && $help) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
193
            }
194
            else
195
            {
196
                $out .= $langs->trans("ErrorNoAccountingCategoryForThisCountry",$mysoc->country_code);
0 ignored issues
show
Bug introduced by
The variable $out seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
197
            }
198
        }
199
        else
200
        {
201
            dol_print_error($db,$db->lasterror());
202
        }
203
        
204
        $out .= ajax_combobox($htmlname, $event);
0 ignored issues
show
Bug introduced by
The variable $out does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $event does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
205
        
206
        print $out;
207
    }
208
}
209
210