javascript::addField()   F
last analyzed

Complexity

Conditions 29
Paths 614

Size

Total Lines 89
Code Lines 64

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 278.2225
Metric Value
cc 29
eloc 64
nc 614
nop 5
dl 0
loc 89
ccs 19
cts 57
cp 0.3333
crap 278.2225
rs 2.2471

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 1
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
/*********************************************************************************
42
43
 * Description:  Creates the runtime database connection.
44
 ********************************************************************************/
45
class javascript{
46
	var $formname = 'form';
47
	var $script = '';
48
	var $sugarbean = null;
49 3
	function setFormName($name){
50 3
		$this->formname = $name;
51 3
	}
52
53 3
	function __construct(){
54 3
		global $app_strings, $current_user, $sugar_config;
55
56
        // Bug 24730 - default initialize the bean object in case we never set it to the current bean object
57 3
		$this->sugarbean = new stdClass;
58 3
		$this->sugarbean->field_name_map = array();
59 3
		$this->sugarbean->module_dir = '';
60 3
	}
61
62
    /**
63
     * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
64
     */
65
    function javascript(){
66
        $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
67
        if(isset($GLOBALS['log'])) {
68
            $GLOBALS['log']->deprecated($deprecatedMessage);
69
        }
70
        else {
71
            trigger_error($deprecatedMessage, E_USER_DEPRECATED);
72
        }
73
        self::__construct();
74
    }
75
76
77 3
	function setSugarBean($sugar){
78 3
		$this->sugarbean = $sugar;
79 3
	}
80
81
	function addRequiredFields($prefix=''){
82
			if(isset($this->sugarbean->required_fields)){
83
				foreach($this->sugarbean->required_fields as $field=>$value){
84
					$this->addField($field,'true', $prefix);
85
				}
86
			}
87
	}
88
89 3
    function addSpecialField($dispField, $realField, $type, $required, $prefix = '') {
90 3
       if (isset($this->sugarbean->field_name_map[$realField]['vname'])) {
91 3
    	$this->addFieldGeneric($dispField, 'date', $this->sugarbean->field_name_map[$realField]['vname'], $required, $prefix );
92
       }
93 3
    }
94
95 3
	function addField($field,$required, $prefix='', $displayField='', $translate = false){
96 3
		if ($field == "id") return;
97 3
        if(isset($this->sugarbean->field_name_map[$field]['vname'])){
98 3
            $vname = $this->sugarbean->field_name_map[$field]['vname'];
99 3
            if ( $translate )
100 3
                $vname = $this->buildStringToTranslateInSmarty($this->sugarbean->field_name_map[$field]['vname']);
101 3
			if(empty($required)){
102 3
				if(isset($this->sugarbean->field_name_map[$field]['required']) && $this->sugarbean->field_name_map[$field]['required']){
103 3
					$required = 'true';
104
				}else{
105 3
					$required = 'false';
106
				}
107 3
				if(isset($this->sugarbean->required_fields[$field]) && $this->sugarbean->required_fields[$field]){
108
					$required = 'true';
109
				}
110 3
				if($field == 'id'){
111
					$required = 'false';
112
				}
113
114
			}
115 3
			if(isset($this->sugarbean->field_name_map[$field]['validation'])){
116
				switch($this->sugarbean->field_name_map[$field]['validation']['type']){
117
					case 'range':
118
                        $min = false;
119
                        $max = false;
120
						if(isset($this->sugarbean->field_name_map[$field]['validation']['min'])){
121
                            $min = filter_var($this->sugarbean->field_name_map[$field]['validation']['min'], FILTER_VALIDATE_INT);
122
						}
123
						if(isset($this->sugarbean->field_name_map[$field]['validation']['max'])){
124
                            $max = filter_var($this->sugarbean->field_name_map[$field]['validation']['max'], FILTER_VALIDATE_INT);
125
						}
126
                        if ($min !== false && $max !== false && $min > $max)
127
                        {
128
							$max = $min;
129
						}
130
						if(!empty($displayField)){
131
							$dispField = $displayField;
132
						}
133
						else{
134
							$dispField = $field;
135
						}
136
						$this->addFieldRange($dispField,$this->sugarbean->field_name_map[$field]['type'],$vname,$required,$prefix, $min, $max );
137
						break;
138
					case 'isbefore':
139
						$compareTo = $this->sugarbean->field_name_map[$field]['validation']['compareto'];
140
						if(!empty($displayField)){
141
							$dispField = $displayField;
142
						}
143
						else{
144
							$dispField = $field;
145
						}
146
						if(!empty($this->sugarbean->field_name_map[$field]['validation']['blank']) && $this->sugarbean->field_name_map[$field]['validation']['blank'])
147
						$this->addFieldDateBeforeAllowBlank($dispField,$this->sugarbean->field_name_map[$field]['type'],$vname,$required,$prefix, $compareTo );
148
						else $this->addFieldDateBefore($dispField,$this->sugarbean->field_name_map[$field]['type'],$vname,$required,$prefix, $compareTo );
149
						break;
150
                    // Bug #47961 Adding new type of validation: through callback function
151
                    case 'callback' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
152
                        $dispField = $displayField ? $displayField : $field;
153
                        $this->addFieldCallback($dispField, $this->sugarbean->field_name_map[$field]['type'], $vname, $required, $prefix, $this->sugarbean->field_name_map[$field]['validation']['callback']);
154
                        break;
155
					default:
156
						if(!empty($displayField)){
157
							$dispField = $displayField;
158
						}
159
						else{
160
							$dispField = $field;
161
						}
162
163
						$type = (!empty($this->sugarbean->field_name_map[$field]['custom_type']))?$this->sugarbean->field_name_map[$field]['custom_type']:$this->sugarbean->field_name_map[$field]['type'];
164
165
						$this->addFieldGeneric($dispField,$type,$vname,$required,$prefix );
166
						break;
167
				}
168
			}else{
169 3
				if(!empty($displayField)){
170
							$dispField = $displayField;
171
						}
172
						else{
173 3
							$dispField = $field;
174
						}
175 3
					$type = (!empty($this->sugarbean->field_name_map[$field]['custom_type']))?$this->sugarbean->field_name_map[$field]['custom_type']:$this->sugarbean->field_name_map[$field]['type'];
176 3
					if(!empty($this->sugarbean->field_name_map[$dispField]['isMultiSelect']))$dispField .='[]';
177 3
					$this->addFieldGeneric($dispField,$type,$vname,$required,$prefix );
178
			}
179
		}else{
180
			$GLOBALS['log']->debug('No VarDef Label For ' . $field . ' in module ' . $this->sugarbean->module_dir );
181
		}
182
183 3
	}
184
185
186 3
	function stripEndColon($modString)
187
	{
188 3
		if(substr($modString, -1, 1) == ":")
189 2
			$modString = substr($modString, 0, (strlen($modString) - 1));
190 3
		if(substr($modString, -2, 2) == ": ")
191
			$modString = substr($modString, 0, (strlen($modString) - 2));
192 3
		return $modString;
193
194
	}
195
196 3
	function addFieldGeneric($field, $type,$displayName, $required, $prefix=''){
197 3
		$this->script .= "addToValidate('".$this->formname."', '".$prefix.$field."', '".$type . "', {$this->getRequiredString($required)},'"
198 3
                       . $this->stripEndColon(translate($displayName,$this->sugarbean->module_dir)) . "' );\n";
199 3
	}
200
201
    // Bug #47961 Generator of callback validator
202
    function addFieldCallback($field, $type, $displayName, $required, $prefix, $callback)
203
    {
204
        $this->script .= 'addToValidateCallback("'
205
            . $this->formname . '", "'
206
            . $prefix.$field . '", "'
207
            . $type . '", '
208
            . $this->getRequiredString($required) . ', "'
209
            . $this->stripEndColon(translate($displayName, $this->sugarbean->module_dir)).'", '
210
            .$callback
211
        .');'."\n";
212
    }
213
214
	function addFieldRange($field, $type,$displayName, $required, $prefix='',$min, $max){
215
        $this->script .= "addToValidateRange("
216
            . "'" . $this->formname . "', "
217
            . "'" . $prefix . $field . "', '"
218
            . $type . "', "
219
            . $this->getRequiredString($required) . ", '"
220
            . $this->stripEndColon(translate($displayName, $this->sugarbean->module_dir)) . "', "
221
            . ($min === false ? 'false' : $min) . ", "
222
            . ($max === false ? 'false' : $max)
223
            . ");\n";
224
	}
225
226
	function addFieldIsValidDate($field, $type, $displayName, $msg, $required, $prefix='') {
227
		$name = $prefix.$field;
228
		$req = $this->getRequiredString($required);
229
		$this->script .= "addToValidateIsValidDate('{$this->formname}', '{$name}', '{$type}', {$req}, '{$msg}');\n";
230
	}
231
232
	function addFieldIsValidTime($field, $type, $displayName, $msg, $required, $prefix='') {
233
		$name = $prefix.$field;
234
		$req = $this->getRequiredString($required);
235
		$this->script .= "addToValidateIsValidTime('{$this->formname}', '{$name}', '{$type}', {$req}, '{$msg}');\n";
236
	}
237
238
	function addFieldDateBefore($field, $type,$displayName, $required, $prefix='',$compareTo){
239
		$this->script .= "addToValidateDateBefore('".$this->formname."', '".$prefix.$field."', '".$type . "', {$this->getRequiredString($required)},'"
240
                       . $this->stripEndColon(translate($displayName,$this->sugarbean->module_dir)) . "', '$compareTo' );\n";
241
	}
242
243
	function addFieldDateBeforeAllowBlank($field, $type, $displayName, $required, $prefix='', $compareTo, $allowBlank='true'){
244
		$this->script .= "addToValidateDateBeforeAllowBlank('".$this->formname."', '".$prefix.$field."', '".$type . "', {$this->getRequiredString($required)},'"
245
                       . $this->stripEndColon(translate($displayName,$this->sugarbean->module_dir)) . "', '$compareTo', '$allowBlank' );\n";
246
	}
247
248 3
	function addToValidateBinaryDependency($field, $type, $displayName, $required, $prefix='',$compareTo){
249 3
		$this->script .= "addToValidateBinaryDependency('".$this->formname."', '".$prefix.$field."', '".$type . "', {$this->getRequiredString($required)},'"
250 3
                       . $this->stripEndColon(translate($displayName,$this->sugarbean->module_dir)) . "', '$compareTo' );\n";
251 3
	}
252
253
    function addToValidateComparison($field, $type, $displayName, $required, $prefix='',$compareTo){
254
        $this->script .= "addToValidateComparison('".$this->formname."', '".$prefix.$field."', '".$type . "', {$this->getRequiredString($required)},'"
255
                       . $this->stripEndColon(translate($displayName,$this->sugarbean->module_dir)) . "', '$compareTo' );\n";
256
    }
257
258
    function addFieldIsInArray($field, $type, $displayName, $required, $prefix, $arr, $operator){
259
    	$name = $prefix.$field;
260
		$req = $this->getRequiredString($required);
261
		$json = getJSONobj();
262
		$arr = $json->encode($arr);
263
		$this->script .= "addToValidateIsInArray('{$this->formname}', '{$name}', '{$type}', {$req}, '".$this->stripEndColon(translate($displayName,$this->sugarbean->module_dir))."', '{$arr}', '{$operator}');\n";
264
    }
265
266 3
	function addAllFields($prefix,$skip_fields=null, $translate = false){
267 3
		if (!isset($skip_fields))
268
		{
269 3
			$skip_fields = array();
270
		}
271 3
		foreach($this->sugarbean->field_name_map as $field=>$value){
272 3
			if (!isset($skip_fields[$field]))
273
			{
274 3
			    if(isset($value['type']) && ($value['type'] == 'datetimecombo' || $value['type'] == 'datetime')) {
275 3
			    	$isRequired = (isset($value['required']) && $value['required']) ? 'true' : 'false';
276 3
			        $this->addSpecialField($value['name'] . '_date', $value['name'], 'datetime', $isRequired);
277 3
                    if ($value['type'] != 'link'  && isset($this->sugarbean->field_name_map[$field]['validation'])) {
278
                        //datetime should also support the isbefore or other type of validate
279 3
                        $this->addField($field, '', $prefix,'',$translate);
280
                    }
281 3
			    } else if (isset($value['type'])) {
282 3
					if ($value['type'] != 'link') {
283 3
			  			$this->addField($field, '', $prefix,'',$translate);
284
					}
285
				}
286
			}
287
		}
288 3
	}
289
290
    function addActionMenu() {
291
        $this->script .= "$(document).ready(SUGAR.themes.actionMenu);";
292
    }
293
294 3
	function getScript($showScriptTag = true, $clearValidateFields = true){
295 3
		$tempScript = $this->script;
296 3
		$this->script = "";
297 3
		if($showScriptTag){
298 3
			$this->script = "<script type=\"text/javascript\">\n";
299
		}
300
301 3
        if($clearValidateFields){
302 3
            $this->script .= "addForm('{$this->formname}');";
303
        }
304
305 3
		$this->script .= $tempScript;
306
307 3
		if($showScriptTag){
308 3
			$this->script .= "</script>";
309
		}
310 3
		return $this->script;
311
	}
312
313 3
    function buildStringToTranslateInSmarty(
314
        $string
315
        )
316
    {
317 3
        if ( is_array($string) ) {
318
            $returnstring = '';
319
            foreach ( $string as $astring )
320
                $returnstring .= $this->buildStringToTranslateInSmarty($astring);
321
            return $returnstring;
322
        }
323 3
        return "{/literal}{sugar_translate label='$string' module='{$this->sugarbean->module_dir}' for_js=true}{literal}";
324
    }
325
326 3
    protected function getRequiredString($required)
327
    {
328 3
        if (is_string($required) && strtolower($required) == "false")
329
        {
330 3
            return "false";
331
        }
332 3
        return empty($required) ? "false" : "true";
333
    }
334
}
335
?>
336