FormFieldExplanationExtension::CMSLink()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
1
<?php
0 ignored issues
show
Coding Style introduced by
File has mixed line endings; this may cause incorrect results
Loading history...
2
3
/**
4
 *@author nicolaas[at]sunnysideup.co.nz
5
 *@description contains a list of form field and their explantions
6
 *
7
 **/
8
9
10
class FormFieldExplanationExtension extends Extension
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
    public static $allowed_actions = array("addfieldexplanation");
13
14
    public static function add_explanations($form, $datarecord)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
15
    {
16
        $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`";
17
        $js = '
18
			var formFieldExplanationErrorMessage = new Array();';
19
        $dos = DataObject::get("FormFieldExplanation", "{$bt}ParentID{$bt} = ".$datarecord->ID);
20
        $explanations = array();
21
        if ($dos) {
22
            foreach ($dos as $do) {
23
                if ($do->Explanation) {
24
                    $explanations[$do->Name]["Explanation"] = $do->Explanation;
25
                }
26
                if ($do->CustomErrorMessage) {
27
                    $explanations[$do->Name]["CustomErrorMessage"] = $do->CustomErrorMessage;
28
                }
29
                if ($do->CustomErrorMessageAdditional) {
30
                    $explanations[$do->Name]["CustomErrorMessageAdditional"] = $do->CustomErrorMessageAdditional;
31
                }
32
                if ($do->AlternativeFieldLabel) {
33
                    $explanations[$do->Name]["AlternativeFieldLabel"] = $do->AlternativeFieldLabel;
34
                }
35
                if ($do->ID) {
36
                    $explanations[$do->Name]["ID"] = $do->ID;
37
                }
38
            }
39
        }
40
        $dos = $do = null;
0 ignored issues
show
Unused Code introduced by
$do is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$dos is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
41
        $dataFields = $form->fields();
42
        $extraFields = new FieldSet();
43
        if ($dataFields) {
44
            foreach ($dataFields as $field) {
45
                if ($field instanceof CompositeField) {
46
                    self::find_composite_fields($field, $extraFields);
47
                }
48
            }
49
        }
50
        if ($dataFields) {
51
            foreach ($dataFields as $field) {
52
                self::process_field($field, $explanations, $datarecord, $js);
53
            }
54
        }
55
        if ($extraFields) {
56
            foreach ($extraFields as $field) {
57
                self::process_field($field, $explanations, $datarecord, $js);
58
            }
59
        }
60
        // block prototype validation
61
        Requirements::javascript(THIRDPARTY_DIR."/jquery/jquery.js");
62
        Requirements::block("sapphire/javascript/Validator.js");
0 ignored issues
show
Documentation introduced by
'sapphire/javascript/Validator.js' is of type string, but the function expects a object<unknown_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
63
        Requirements::javascript("formfieldexplanations/javascript/Silvertripe-2.3-Validator.js");
64
        Requirements::javascript("formfieldexplanations/javascript/formfieldexplanations.js");
65
        Requirements::customScript($js, "FormFieldExplanationExtension");
0 ignored issues
show
Documentation introduced by
'FormFieldExplanationExtension' is of type string, but the function expects a object<Use>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
66
        Requirements::themedCSS("formfieldexplanations");
67
        return $form;
68
    }
69
70
    protected static function find_composite_fields($compositeField, &$extraFields)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
71
    {
72
        $dataFields = $compositeField->FieldSet();
73
        if ($dataFields) {
74
            foreach ($dataFields as $field) {
75
                if ($field instanceof CompositeField) {
76
                    self::find_composite_fields($field, $extraFields);
77
                } else {
78
                    $extraFields->push($field);
79
                }
80
            }
81
        }
82
        return $extraFields;
83
    }
84
85
    protected static function process_field($field, $explanations, $datarecord, &$js)
86
    {
87
        $dos = $do = null;
0 ignored issues
show
Unused Code introduced by
$do is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
Unused Code introduced by
$dos is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
88
        if ($name = $field->Name()) {
89
            $message = '';
90
            if (isset($explanations[$name])) {
91
                if (isset($explanations[$name]["Explanation"])) {
92
                    $message .= $explanations[$name]["Explanation"];
93
                }
94
                if ($datarecord->canEdit() && isset($explanations[$name]["ID"])) {
95
                    $message .= ' | '.self::CMSLink($datarecord->ID, $explanations[$name]["ID"]);
96
                }
97
            } elseif ($datarecord->canEdit() && $name) {
98
                $title = $field->Title();
99
                if (!$title) {
100
                    $title = $name;
101
                }
102
                $cleanTitle = strip_tags($title);
103
                if (class_exists("UserDefinedForm")) {
104
                    $cleanTitle = str_replace(UserDefinedForm::$required_identifier, "", $cleanTitle);
105
                    $cleanTitle = str_replace("+", "", $cleanTitle);
106
                }
107
                $message .= ' | <a href="'.$datarecord->Link().'addfieldexplanation/'.urlencode($name).'/'.urlencode($cleanTitle).'/" class="addFieldExplanation">customise field</a>';
108
            }
109
            $do = true;
110
            switch ($field->class) {
111
                case "HeaderField":
112
                    $do = false;
113
                    break;
114
                default:
115
                    break;
116
            }
117
            $id = $field->id();
118
            $message = str_replace("/", "\/", Convert::raw2js($message));
119
            if ($do && $message && $name && $id) {
120
                $js .= "
121
				formfieldexplanations.add_info('".$name."', '".$message."', '".$id."');";
122
            }
123
        }
124
        $errorMessage = '';
125
        if (isset($explanations[$name]["CustomErrorMessage"])) {
126
            $errorMessage = $explanations[$name]["CustomErrorMessage"];
127
            if (isset($explanations[$name]["CustomErrorMessageAdditional"])) {
128
                $errorMessage .= '<span class="additionalValidationErrorMessage">'.$explanations[$name]["CustomErrorMessageAdditional"].'</span>';
129
            }
130
            $field->addExtraClass("customErrorMessage");
131
            $field->setCustomValidationMessage($errorMessage);
132
        }
133
        if ($field->Required() && $errorMessage) {
134
            $js .= "
135
				formFieldExplanationErrorMessage['$name'] = '".str_replace("/", "\/", Convert::raw2js($errorMessage))."';";
136
        }
137
        if (isset($explanations[$name]["AlternativeFieldLabel"])) {
138
            $js .= "
139
				formfieldexplanations.replace_title('".$name."', '".str_replace("/", "\/", Convert::raw2js($explanations[$name]["AlternativeFieldLabel"]))."', '".$id."');";
0 ignored issues
show
Bug introduced by
The variable $id 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...
140
        }
141
    }
142
143
    public function addfieldexplanation(HTTPRequest $HTTPRequest)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
144
    {
145
        $bt = defined('DB::USE_ANSI_SQL') ? "\"" : "`";
146
        $fieldName = $HTTPRequest->param("ID");
147
        $fieldTitle = $HTTPRequest->param("OtherID");
148
        $obj = DataObject::get_one("FormFieldExplanation", "{$bt}Name{$bt} = '".$fieldName."' AND ParentID = ".$this->owner->ID);
149
        if (!$obj) {
150
            $obj = new FormFieldExplanation();
151
        }
152
        $obj->Name = $fieldName;
153
        $obj->Title = $fieldTitle;
154
        $obj->Explanation = "explanation to be added";
155
        $obj->ParentID = $this->owner->ID;
156
        $obj->write();
157
        if (Director::is_ajax()) {
158
            return self::CMSLink($this->owner->ID, $obj->ID);
159
        } else {
160
            Director::redirectBack();
0 ignored issues
show
Deprecated Code introduced by
The method Director::redirectBack() has been deprecated with message: 2.5 Use Controller->redirectBack()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
161
        }
162
    }
163
164
    protected function editfieldexplanation(HTTPRequest $HTTPRequest)
0 ignored issues
show
Unused Code introduced by
The parameter $HTTPRequest is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
165
    {
166
        $customiseArray = array(
0 ignored issues
show
Unused Code introduced by
$customiseArray is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
167
            "Title" => "Test",
168
            "Form" => "FormTest"
169
        );
170
        //TO DO!!!!! link with DataObjectsorter
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
171
        return array();
172
    }
173
174
    protected static function CMSLink($pageID, $itemID)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
175
    {
176
        if (class_exists("DataObjectOneRecordUpdateController")) {
177
            $link = DataObjectOneRecordUpdateController::popup_link(
178
                $className = "FormFieldExplanation",
179
                $recordID = $itemID,
180
                $linkText = "edit customisation"
181
            );
182
            return $link;
183
        } else {
184
            return '<a href="admin/show/'.$pageID.'" class="editFieldExplanation">edit description in CMS</a>';
185
        }
186
    }
187
188
    protected function array2json($array)
189
    {
190
        foreach ($array as $key => $value) {
191
            if (is_array($value)) {
192
                $result[] = "$key:" . $this->array2json($value);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$result was never initialized. Although not strictly required by PHP, it is generally a good practice to add $result = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
193
            } else {
194
                $value = (is_bool($value)) ? $value : "\"$value\"";
195
                $result[] = "$key:$value \n";
0 ignored issues
show
Bug introduced by
The variable $result 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...
196
            }
197
        }
198
        return (isset($result)) ? "{\n".implode(', ', $result) ."} \n": '{}';
199
    }
200
}
201