FormBuilderController::getForeach()   D
last analyzed

Complexity

Conditions 9
Paths 18

Size

Total Lines 41
Code Lines 20

Duplication

Lines 20
Ratio 48.78 %

Importance

Changes 0
Metric Value
cc 9
eloc 20
nc 18
nop 11
dl 20
loc 41
rs 4.909
c 0
b 0
f 0

How to fix   Many Parameters   

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
3
namespace App\Plugins\ServiceDesk\Controllers\FormBuilder;
4
5
use App\Plugins\ServiceDesk\Controllers\BaseServiceDeskController;
6
use Illuminate\Http\Request;
7
use App\Plugins\ServiceDesk\Model\FormBuilder\Form;
8
use App\Plugins\ServiceDesk\Model\FormBuilder\FormValue;
9
use App\Plugins\ServiceDesk\Model\FormBuilder\FormField;
10
use Exception;
11
12
class FormBuilderController extends BaseServiceDeskController {
13
14
    /**
15
     * Create a new controller instance.
16
     *
17
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
18
     */
19
    public function __construct() {
20
        $this->middleware('auth');
21
    }
22
23
    public function create() {
24
        return view('service::form-builder.create');
25
    }
26
27
    public function store(Request $request) {
28
        $this->validate($request, [
29
            'title' => 'required|unique:sd_forms',
30
            'form' => 'required',
31
        ]);
32
        try {
33
            $forms = new Form();
34
            $form = $request->input('form');
35
            $title = $request->input('title');
36
            $xmlNode = simplexml_load_string($form);
37
            $forms->title = $title;
0 ignored issues
show
Documentation introduced by
The property title does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
38
            $forms->save();
39
            $arrayData = \App\Plugins\ServiceDesk\Controllers\Library\UtilityController::xmlToArray($xmlNode);
40
            $save = $this->saveField($forms->id, $arrayData);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
41
            $result = ["fails" => "We can't process your request"];
42
            if ($save) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $save of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
43
                $result = ["success" => "Form $forms->title created successfully"];
0 ignored issues
show
Documentation introduced by
The property title does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
44
            }
45
            return response()->json(compact('result'));
46
        } catch (Exception $ex) {
47
            dd($ex);
48
            $result = ["fails" => $ex->getMessage()];
49
            return response()->json(compact('result'));
50
        }
51
    }
52
53
    public function saveField($formid, $data) {
54
        //dd($data);
55
        $fields = new FormField();
56
        $items = $fields->where('form_id', $formid)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Plugins\Servi...\FormBuilder\FormField>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
57
        if ($items->count() > 0) {
58
            foreach ($items as $item) {
59
                $item->delete();
60
            }
61
        }
62
        foreach ($data['form-template']['fields']['field'] as $index => $item) {
63
            $field = $fields->create([
64
                'name' => $this->checkField('name', $item),
65
                'label' => $this->checkField('label', $item),
66
                'form_id' => $formid,
67
                'type' => $this->checkField('type', $item),
68
                'sub_type' => $this->checkField('subtype', $item),
69
                'class' => $this->checkField('class', $item),
70
                'is_required' => $this->checkField('required', $item),
71
                'placeholder' => $this->checkField('placeholder', $item),
72
                'description' => $this->checkField('description', $item),
73
                'multiple' => $this->checkField('multiple', $item),
74
                'role' => $this->checkField('role', $item),
75
            ]);
76
            if (is_string($item)) {
77
                if ($index == "option") {
78
                    $this->saveFieldValue($field->id, $item['option']);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Plugins\Servi...\FormBuilder\FormField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
$item['option'] is of type string, but the function expects a array.

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...
79
                }
80
            } elseif (key_exists('option', $item)) {
81
                $this->saveFieldValue($field->id, $item['option']);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Plugins\Servi...\FormBuilder\FormField>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
82
            }
83
        }
84
        if ($field) {
0 ignored issues
show
Bug introduced by
The variable $field 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...
85
            return "success";
86
        }
87
    }
88
89
    public function saveFieldValue($fieldid, $options = []) {
90
        $values = new FormValue();
91
        foreach ($options as $option) {
92
            $values->create([
93
                'field_id' => $fieldid,
94
                'option' => $option['option-name'],
95
                'value' => $option['value'],
96
            ]);
97
        }
98
    }
99
100
    public function checkField($name, $array) {
101
        $res = "";
102
        if (is_string($array)) {
103
            $res = $array;
104
        } elseif (key_exists($name, $array)) {
105
            $res = $array[$name];
106
        }
107
        return $res;
108
    }
109
110
    public function renderHtmlByFormId($id, $view = true, $assetid = '') {
111
        $html = "";
112
        $forms = new \App\Plugins\ServiceDesk\Model\Assets\AssetFormRelation();
113
        $form = $forms->where('asset_type_id', $id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Plugins\Servi...sets\AssetFormRelation>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
114
        if ($form) {
115
            $title = $form->title;
116
            $html = "<h1>$title</h1>" . $this->getFields($form->id, $assetid);
117
        }
118
        if ($view == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
119
            return view("service::form-builder.show", compact('html'));
120
        } else {
121
            return $html;
122
        }
123
    }
124
125
    public function getFields($formid, $assetid = '', $json = false) {
126
        $item = "";
127
        $fields = new FormField();
128
        $field = $fields->where('form_id', $formid)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Plugins\Servi...\FormBuilder\FormField>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
129
130
        if ($field->count() > 0) {
131
            foreach ($field as $key => $html) {
132
133
                $name = $this->checkField('name', $html->toArray());
134
135
                $label = $this->checkField('label', $html->toArray());
136
                $type = $this->checkField('type', $html->toArray());
137
                $sub_type = $this->checkField('sub_type', $html->toArray());
138
                $class = $this->checkField('class', $html->toArray());
139
                $is_required = $this->checkField('is_required', $html->toArray());
140
                $placeholder = $this->checkField('placeholder', $html->toArray());
141
                $description = $this->checkField('description', $html->toArray());
142
                $multiple = $this->checkField('multiple', $html->toArray());
143
                $role = $this->checkField('role', $html->toArray());
144
145
                if ($json == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
146
147
                    $item['form-template']['fields'][$key] = $this->getJson($key, $html->id, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $role);
148
                } else {
149
                    //dd([$html->id, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
150
                    //$item .="<form id='form'>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
151
                    $item .= "<div class='form-group col-md-6'>";
152
                    $item .= $this->fields($html->id, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $assetid);
153
                    $item .= "</div>";
154
                }
155
                //$item .= "</form>";
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...
156
            }
157
        }
158
159
        //dd($item);
160
        return $item;
161
    }
162
163
    public function fields($fieldid, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $assetid = '') {
164
        $required = "";
165
        $html = "";
166
        if ($is_required == "true") {
167
            $required = "required";
168
        }
169
        switch ($type) {
170
            case "button":
171
                return "<$sub_type class='$class' name='$name'>$label</$sub_type>";
172
            case "checkbox":
173
                return "<label>$label</label>"
174
                        . "<input type='$type' class='$class' placeholder='$placeholder' name='$name' $required>";
175
            case "paragraph":
176
                return "<$sub_type class='$class'></$sub_type>";
177
            case "header":
178
                return "<$sub_type class='$class'></$sub_type>";
179
            case "textarea":
180
                return "<label>$label</label><$type class='$class' placeholder='$placeholder' $required></$type>";
181
            case "text":
182
                return "<label>$label</label>"
183
                        //.\Form::text($name,null,['class'=>$class,'placeholder'=>$placeholder,'required'=>$is_required]);
0 ignored issues
show
Unused Code Comprehensibility introduced by
88% 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...
184
                        . "<input type='$type' class='$class' placeholder='$placeholder' name='$name' value=" . $this->value($fieldid, $assetid) . " $required>";
185
            case "date":
186
                return "<label>$label</label>"
187
                        . "<input type='$type' class='$class' placeholder='$placeholder' name='$name' $required>";
188
            case "file":
189
                return "<label>$label</label>"
190
                        . "<input type='$type' class='$class' placeholder='$placeholder' name='$name' $required>";
191
            case "checkbox-group":
192
                return $this->groupValue($fieldid, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple);
193
            case "radio-group":
194
                return $this->groupValue($fieldid, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple);
195
            case "select":
196
                return $this->groupValue($fieldid, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple);
197
        }
198
199
        return $html;
200
    }
201
202
    public function groupValue($fieldid, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple, $json = false) {
203
        $values = new FormValue();
204
        $html = "";
0 ignored issues
show
Unused Code introduced by
$html 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...
205
        $value = $values->where('field_id', $fieldid)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Plugins\Servi...\FormBuilder\FormValue>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
206
        $html = $this->getForeach($value, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple, $json);
207
        return $html;
208
    }
209
210
    public function getForeach($values, $name, $label, $type, $sub_type, $class, $required, $placeholder, $description, $multiple, $json) {
0 ignored issues
show
Unused Code introduced by
The parameter $sub_type 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...
Unused Code introduced by
The parameter $description 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...
Unused Code introduced by
The parameter $multiple 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...
211
        $html = "";
212
        $array = [];
0 ignored issues
show
Unused Code introduced by
$array 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...
213
        if (count($values) > 0) {
214 View Code Duplication
            if ($type == "checkbox-group") {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
215
                $html .= "<label>$label</label></br>";
216
                foreach ($values as $index => $value) {
217
                    //if ($json == false) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
218
                    $html .= "<input type='checkbox' name='$name' class='$class' value='$value->value'>" . $value->option . "</br>";
219
//                    } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
220
//                        $array[$index] = $values->lists('option','value')->toArray();
221
//                    }
222
                }
223
            }
224 View Code Duplication
            if ($type == "radio-group") {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
225
                $html .= "<label>$label</label></br>";
226
                foreach ($values as $index => $value) {
227
                    //if ($json == false) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
228
                    $html .= "<input type='radio' name='$name' class='$class' value='$value->value'>" . $value->option . "</br>";
229
//                    } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% 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...
230
//                        $array[$index] = $value->lists('option','value')->toArray();
231
//                    }
232
                }
233
            }
234
            if ($type == "select") {
235
                $html .= "<label>$label</label><select class='$class' name='$name' placeholder='$placeholder' $required>";
236
                foreach ($values as $index => $value) {
237
                    //if ($json == false) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
238
                    $html .= "<option value='$value->value'>" . $value->option . "</option>";
239
                    //} else {
240
                    //$array[$index] = $value->lists('option','value')->toArray();
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
241
                    //}
242
                }
243
                $html .="</select>";
244
            }
245
        }
246
        if ($json == false) {
247
            return $html;
248
        }
249
        return $values->lists('option', 'value')->toArray();
250
    }
251
252
    public function value($formid, $assetid = "") {
253
        $result = "";
254
        if ($assetid !== '') {
255
            $fields = new FormField();
256
            $field = $fields->find($formid);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Plugins\Servi...\FormBuilder\FormField>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
257
            if ($field) {
258
                $name = $field->name;
259
                $asset_forms = new \App\Plugins\ServiceDesk\Model\Assets\AssetForm();
260
                $form = $asset_forms->where('asset_id', $assetid)->where('key', $name)->first();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Plugins\Servi...Model\Assets\AssetForm>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
261
                if ($form) {
262
                    $result = $form->value;
263
                }
264
            }
265
        }
266
        return $result;
267
    }
268
269
    public function index() {
270
        try {
271
            return view('service::form-builder.index');
272
        } catch (Exception $ex) {
273
            return redirect()->back()->with('fails', $ex->getMessage());
274
        }
275
    }
276
277
    public function getForm() {
278
        $forms = new Form();
279
        $form = $forms->select('id', 'title')->get();
0 ignored issues
show
Documentation Bug introduced by
The method select does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
280
        return \Datatable::Collection($form)
281
                        ->showColumns('title')
282
                        ->addColumn('action', function($model) {
283
                            $preview = $this->show($model->id, 'popup');
284
                            $url = url('service-desk/form-builder/'.$model->id.'/delete');
285
                            $title = "Delete $model->title";
286
                            $delete = \App\Plugins\ServiceDesk\Controllers\Library\UtilityController::deletePopUp($model->id, $url, $title);
287
                            return "<a href=" . url('service-desk/form-builder/' . $model->id . '/edit') . " class='btn btn-sm btn-primary'>Edit</a> "
288
                                    . $preview.$delete;
289
                        })
290
                        ->searchColumns('title')
291
                        ->orderColumns('title')
292
                        ->make();
293
    }
294
295
    public function edit($id) {
296
        try {
297
            $title = "";
298
            $forms = new Form();
299
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
300
            if ($form) {
301
                $title = $form->title;
302
            }
303
            $fields = $this->convertForm($id);
304
            $array = $fields->toArray();
305
            $values = \App\Plugins\ServiceDesk\Controllers\Library\UtilityController::arrayToXml($array);
306
            $xml = "<form-template><fields>$values</fields></form-template>";
307
            $xml = str_replace("<field ></field>", '', $xml);
308
            return view("service::form-builder.edit", compact('xml', 'title', 'form'));
309
        } catch (Exception $ex) {
310
            dd($ex);
311
            return redirect()->back()->with('fails', $ex->getMessage());
312
        }
313
    }
314
315
    public function getArray($key, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $role, $options = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $key 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...
Unused Code introduced by
The parameter $is_required 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...
316
        $item['name'] = $name;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$item was never initialized. Although not strictly required by PHP, it is generally a good practice to add $item = 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...
317
        $item['label'] = $label;
318
        $item['type'] = $type;
319
        $item['subtype'] = $sub_type;
320
        $item['class'] = $class;
321
        $item['placeholder'] = $placeholder;
322
        $item['description'] = $description;
323
        $item['multiple'] = $multiple;
324
        $item['role'] = $role;
325
        $item['options'] = $options;
326
        return $item;
327
    }
328
329
    public function getJson($key, $fieldid, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $role, $options = []) {
0 ignored issues
show
Unused Code introduced by
The parameter $options 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...
330
        $options = $this->groupValue($fieldid, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, true);
331
        $array = $this->getArray($key, $name, $label, $type, $sub_type, $class, $is_required, $placeholder, $description, $multiple, $role, $options);
332
        return $array;
333
    }
334
335
    public function convertForm($formid) {
336
        $array = $this->getFields($formid, '', true);
337
        $collection = new \Illuminate\Support\Collection($array);
338
        return $collection;
339
    }
340
341
    public function update($id, Request $request) {
342
        $this->validate($request, [
343
            'title' => 'required|unique:sd_forms',
344
            'form' => 'required',
345
        ]);
346
        try {
347
            $forms = new Form();
348
            $model = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
349
            if (!$model) {
350
                $result = ["fails" => "We can't process your request"];
351
                return response()->json(compact('result'));
352
            }
353
            $form = $request->input('form');
354
            $title = $request->input('title');
355
            $xmlNode = simplexml_load_string($form);
356
            $model->title = $title;
357
            $model->save();
358
            $arrayData = \App\Plugins\ServiceDesk\Controllers\Library\UtilityController::xmlToArray($xmlNode);
359
            $save = $this->saveField($model->id, $arrayData);
360
            $result = ["fails" => "We can't process your request"];
361
            if ($save) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $save of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
362
                $result = ["success" => "Form $forms->title Updated successfully"];
0 ignored issues
show
Documentation introduced by
The property title does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
363
            }
364
            return response()->json(compact('result'));
365
        } catch (Exception $ex) {
366
            $result = ["fails" => $ex->getMessage()];
367
            return response()->json(compact('result'));
368
        }
369
    }
370
371
    public function show($id, $render = 'view') {
372
        try {
373
            $html = "";
374
            $title = "";
375
            $forms = new Form();
376
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
377
            if ($form) {
378
                $title = $form->title;
379
                $html = $this->getFields($form->id);
380
            }
381
            switch ($render) {
382
                case "view":
383
                    $html = "<h1>$title</h1>" . $html;
384
                    return view("service::form-builder.show", compact('html'));
385
                case "popup":
386
                    return $this->popUp($id, $title, $html);
387
                default :
388
                    return $html;
389
            }
390
        } catch (Exception $ex) {
391
            return redirect()->back()->with('fails', $ex->getMessage());
392
        }
393
    }
394
395
    public function popUp($id, $title, $html) {
396
        return '<a href="#form" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#form' . $id . '">Preview</a>
397
                <div class="modal fade" id="form' . $id . '">
398
                    <div class="modal-dialog">
399
                        <div class="modal-content">
400
                            <div class="modal-header">
401
                                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
402
                                <h4 class="modal-title">' . $title . '</h4>
403
                            </div>
404
                            <div class="modal-body">
405
                                <div class="row">
406
                                <div class="col-md-12">
407
                                ' . $html . '
408
                                </div>
409
                                </div>
410
                            </div>
411
                            <div class="modal-footer">
412
                                <button type="button" id="close" class="btn btn-default pull-left" data-dismiss="modal">Close</button>
413
                            </div>
414
                        </div>
415
                    </div>
416
                </div>';
417
    }
418
    
419
    public function delete($id){
420
        try{
421
            $forms = new Form();
422
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Plugins\Servi...Model\FormBuilder\Form>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
423
            if ($form) {
424
               $form->delete(); 
425
            }
426
            return redirect()->back()->with('success', "$form->title deleted successfully");
427
        } catch (Exception $ex) {
428
             return redirect()->back()->with('fails', $ex->getMessage());
429
        }
430
    }
431
432
}
433