Completed
Branch develop (18468e)
by
unknown
23:46
created

modulebuilder.lib.php ➔ rebuildObjectSql()   D

Complexity

Conditions 17
Paths 137

Size

Total Lines 89
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 17
eloc 51
nc 137
nop 5
dl 0
loc 89
rs 4.5364
c 0
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
/* Copyright (C) 2009-2010 Laurent Destailleur  <[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
 * or see http://www.gnu.org/
17
 */
18
19
/**
20
 *  \file		htdocs/core/lib/memory.lib.php
21
 *  \brief		Set of function for memory/cache management
22
 */
23
24
25
26
27
/**
28
 * 	Save data into a memory area shared by all users, all sessions on server
29
 *
30
 *  @param	string      $destdir		Directory
31
 * 	@param	string		$module			Module name
32
 *  @param	string      $objectname		Name of object
33
 * 	@param	string		$newmask		New mask
34
 *  @param	string      $readdir		Directory source (use $destdir when not defined)
35
 * 	@return	int							<=0 if KO, >0 if OK
36
 */
37
function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir='')
38
{
39
    global $db, $langs;
40
41
    if (empty($objectname)) return -1;
42
    if (empty($readdir)) $readdir=$destdir;
43
44
    $pathoffiletoeditsrc=$readdir.'/class/'.strtolower($objectname).'.class.php';
45
    $pathoffiletoedittarget=$destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : '');
46
    if (! dol_is_file($pathoffiletoeditsrc))
47
    {
48
    	$langs->load("errors");
49
        setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
50
        return -1;
51
    }
52
53
    //$pathoffiletoedittmp=$destdir.'/class/'.strtolower($objectname).'.class.php.tmp';
54
    //dol_delete_file($pathoffiletoedittmp, 0, 1, 1);
55
56
    try
57
    {
58
        include_once $pathoffiletoeditsrc;
59
        if (class_exists($objectname)) $object=new $objectname($db);
60
        else return -1;
61
62
        // Backup old file
63
        dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
64
65
        // Edit class files
66
        $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
67
68
        $i=0;
69
        $texttoinsert = '// BEGIN MODULEBUILDER PROPERTIES'."\n";
70
        $texttoinsert.= "\t".'/**'."\n";
71
        $texttoinsert.= "\t".' * @var array  Array with all fields and their property'."\n";
72
        $texttoinsert.= "\t".' */'."\n";
73
        $texttoinsert.= "\t".'public $fields=array('."\n";
74
75
        if (count($object->fields))
76
        {
77
            foreach($object->fields as $key => $val)
78
            {
79
                $i++;
80
                $typephp='';
81
                $texttoinsert.= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',";
82
                $texttoinsert.= " 'visible'=>".($val['visible']?$val['visible']:0).",";
83
                $texttoinsert.= " 'enabled'=>".($val['enabled']?$val['enabled']:0).",";
84
                if ($val['position']) $texttoinsert.= " 'position'=>".$val['position'].",";
85
                if ($val['notnull']) $texttoinsert.= " 'notnull'=>".$val['notnull'].",";
86
                if ($val['index']) $texttoinsert.= " 'index'=>".$val['index'].",";
87
                if ($val['searchall']) $texttoinsert.= " 'searchall'=>".$val['searchall'].",";
88
                if ($val['comment']) $texttoinsert.= " 'comment'=>'".$val['comment']."',";
89
                $texttoinsert.= "),\n";
90
            }
91
        }
92
        $texttoinsert.= "\t".');'."\n";
93
94
        $texttoinsert.= "\n";
95
96
        if (count($object->fields))
97
        {
98
            foreach($object->fields as $key => $val)
99
            {
100
                $i++;
101
                $typephp='';
102
                $texttoinsert.= "\t".'public $'.$key.$typephp.";";
103
                //if ($key == 'rowid')  $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
104
                //if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
105
                //$texttoinsert.= ($val['notnull']?' NOT NULL':'');
106
                //if ($i < count($object->fields)) $texttoinsert.=";";
107
                $texttoinsert.= "\n";
108
            }
109
        }
110
111
        $texttoinsert.= "\t".'// END MODULEBUILDER PROPERTIES';
112
113
        $contentclass = preg_replace('/\/\/ BEGIN MODULEBUILDER PROPERTIES.*END MODULEBUILDER PROPERTIES/ims', $texttoinsert, $contentclass);
114
115
        dol_mkdir(dirname($pathoffiletoedittarget));
116
117
        //file_put_contents($pathoffiletoedittmp, $contentclass);
118
        file_put_contents(dol_osencode($pathoffiletoedittarget), $contentclass);
119
        @chmod($pathoffiletoedittarget, octdec($newmask));
120
121
        return 1;
122
    }
123
    catch(Exception $e)
124
    {
125
        print $e->getMessage();
126
        return -1;
127
    }
128
}
129
130
/**
131
 * 	Save data into a memory area shared by all users, all sessions on server
132
 *
133
 *  @param	string      $destdir		Directory
134
 * 	@param	string		$module			Module name
135
 *  @param	string      $objectname		Name of object
136
 * 	@param	string		$newmask		New mask
137
 *  @param	string      $readdir		Directory source (use $destdir when not defined)
138
 * 	@return	int							<=0 if KO, >0 if OK
139
 */
140
function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir='')
141
{
142
    global $db, $langs;
143
144
    if (empty($objectname)) return -1;
145
    if (empty($readdir)) $readdir=$destdir;
146
147
    $pathoffiletoclasssrc=$readdir.'/class/'.strtolower($objectname).'.class.php';
148
149
    // Edit .sql file
150
    $pathoffiletoeditsrc=$readdir.'/sql/llx_'.strtolower($objectname).'.sql';
151
    $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : '');
152
	if (! dol_is_file($pathoffiletoeditsrc))
153
    {
154
    	$langs->load("errors");
155
    	setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors');
156
    	return -1;
157
    }
158
159
    try
160
    {
161
    	include_once $pathoffiletoclasssrc;
162
        if (class_exists($objectname)) $object=new $objectname($db);
163
        else return -1;
164
    }
165
    catch(Exception $e)
166
    {
167
        print $e->getMessage();
168
    }
169
170
    // Backup old file
171
    dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1);
172
173
    $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
174
175
    $i=0;
176
    $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n";
177
    if (count($object->fields))
178
    {
179
        foreach($object->fields as $key => $val)
180
        {
181
            $i++;
182
            $texttoinsert.= "\t".$key." ".$val['type'];
183
            if ($key == 'rowid')  $texttoinsert.= ' AUTO_INCREMENT PRIMARY KEY';
184
            if ($key == 'entity') $texttoinsert.= ' DEFAULT 1';
185
            $texttoinsert.= ($val['notnull']?' NOT NULL':'');
186
            if ($i < count($object->fields)) $texttoinsert.=", ";
0 ignored issues
show
Bug introduced by
The variable $object 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...
187
            $texttoinsert.= "\n";
188
        }
189
    }
190
    $texttoinsert.= "\t".'-- END MODULEBUILDER FIELDS';
191
192
    $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql);
193
194
    file_put_contents($pathoffiletoedittarget, $contentsql);
195
    @chmod($pathoffiletoedittarget, octdec($newmask));
196
197
198
    // Edit .key.sql file
199
    $pathoffiletoeditsrc=$destdir.'/sql/llx_'.strtolower($objectname).'.key.sql';
200
    $pathoffiletoedittarget=$destdir.'/sql/llx_'.strtolower($objectname).'.key.sql'.($readdir != $destdir ? '.new' : '');
201
202
    $contentsql = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r');
203
204
    $i=0;
205
    $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n";
206
    if (count($object->fields))
207
    {
208
        foreach($object->fields as $key => $val)
209
        {
210
            $i++;
211
            if ($val['index'])
212
            {
213
                $texttoinsert.= "ALTER TABLE llx_".strtolower($objectname)." ADD INDEX idx_".strtolower($objectname)."_".$key." (".$key.");";
214
                $texttoinsert.= "\n";
215
            }
216
        }
217
    }
218
    $texttoinsert.= '-- END MODULEBUILDER INDEXES';
219
220
    $contentsql = preg_replace('/-- BEGIN MODULEBUILDER INDEXES.*END MODULEBUILDER INDEXES/ims', $texttoinsert, $contentsql);
221
222
    dol_mkdir(dirname($pathoffiletoedittarget));
223
224
    file_put_contents($pathoffiletoedittarget, $contentsql);
225
    @chmod($pathoffiletoedittarget, octdec($newmask));
226
227
    return 1;
228
}
229
230
231