FormController   D
last analyzed

Complexity

Total Complexity 98

Size/Duplication

Total Lines 611
Duplicated Lines 17.35 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
dl 106
loc 611
rs 4.828
c 0
b 0
f 0
wmc 98
lcom 2
cbo 7

28 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
A home() 0 4 1
A index() 0 8 2
A create() 0 8 2
A show() 16 16 3
B store() 0 38 4
A delete() 0 16 3
A edit() 17 17 3
A addChildForm() 17 17 3
C update() 0 48 7
A renderForm() 0 14 3
C getType() 23 23 10
B getAttribute() 21 21 9
D getForm() 12 34 10
B createValues() 0 23 6
A addChild() 0 21 4
A renderChild() 0 18 3
B jqueryScript() 0 30 3
B jqueryCheckboxScript() 0 34 2
B jquerySelectScript() 0 34 2
A selectForm() 0 11 1
A radioForm() 0 16 3
A checkboxForm() 0 22 3
A requiredStyle() 0 12 1
A requiredClass() 0 9 2
A setSession() 0 6 1
A getSession() 0 9 2
A removeUnderscoreFromDB() 0 11 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like FormController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FormController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers\Admin\helpdesk;
4
5
// Controller
6
use App\Http\Controllers\Controller;
7
// Model
8
use App\Model\helpdesk\Form\Fields;
9
use App\Model\helpdesk\Form\Forms;
10
use App\Model\helpdesk\Manage\Help_topic;
11
// Request
12
use Exception;
13
// Class
14
use Form;
15
use Illuminate\Http\Request;
16
use Input;
17
use Lang;
18
use Redirect;
19
20
/**
21
 * FormController
22
 * This controller is used to CRUD Custom Forms.
23
 *
24
 * @author      Ladybird <[email protected]>
25
 */
26
class FormController extends Controller
27
{
28
    private $fields;
29
    private $forms;
30
31
    public function __construct(Fields $fields, Forms $forms)
32
    {
33
        $this->fields = $fields;
34
        $this->forms = $forms;
35
        $this->middleware('auth', [
36
            'except' => [
37
                'renderForm',
38
                'getType',
39
                'getAttribute',
40
                'getForm',
41
                'createValues',
42
                'addChild',
43
                'renderChild',
44
                'jqueryScript',
45
                'jqueryCheckboxScript',
46
                'jquerySelectScript',
47
            ],
48
        ]);
49
    }
50
51
    /**
52
     * home.
53
     *
54
     * @return type
55
     */
56
    public function home()
57
    {
58
        return view('forms.home');
59
    }
60
61
    /**
62
     * list of forms.
63
     *
64
     * @param type Forms $forms
65
     *
66
     * @return Response
67
     */
68
    public function index(Forms $forms)
69
    {
70
        try {
71
            return view('themes.default1.admin.helpdesk.manage.form.index', compact('forms'));
72
        } catch (Exception $e) {
73
            return redirect()->back()->with('fails', $e->getMessage());
74
        }
75
    }
76
77
    /**
78
     * create a new form.
79
     *
80
     * @return Response
81
     */
82
    public function create()
83
    {
84
        try {
85
            return view('themes.default1.admin.helpdesk.manage.form.form');
86
        } catch (Exception $e) {
87
            return redirect()->back()->with('fails', $e->getMessage());
88
        }
89
    }
90
91
    /**
92
     * Show a new form.
93
     *
94
     * @param int $id
95
     *
96
     * @return Response
97
     */
98 View Code Duplication
    public function show($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
99
    {
100
        try {
101
            $forms = new Forms();
102
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
103
            //dd($form);
104
            if ($form) {
105
                $fields = $form->fields();
106
107
                return view('themes.default1.admin.helpdesk.manage.form.preview', compact('form', 'fields'));
108
            }
109
            throw new Exception("Sorry we can't find your request");
110
        } catch (Exception $ex) {
111
            return redirect()->back()->with('fails', $ex->getMessage());
112
        }
113
    }
114
115
    /**
116
     * Store a new form.
117
     *
118
     * @return Response
119
     */
120
    public function store(Request $request)
121
    {
122
        $this->validate($request, [
123
            'formname' => 'required|unique:custom_forms,formname',
124
            'label.*'  => 'required',
125
            'name.*'   => 'required',
126
            'type.*'   => 'required',
127
        ]);
128
        try {
129
            $forms = new Forms();
130
            $require = Input::get('required');
131
132
            $forms->formname = Input::get('formname');
0 ignored issues
show
Documentation introduced by
The property formname does not exist on object<App\Model\helpdesk\Form\Forms>. 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...
133
            $forms->save();
134
            $count = count(Input::get('name'));
135
            $fields = [];
0 ignored issues
show
Unused Code introduced by
$fields 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...
136
            for ($i = 0; $i <= $count; $i++) {
137
                if (!empty(Input::get('name')[$i])) {
138
                    $name = str_slug(Input::get('name')[$i], '_');
139
                    $field = Fields::create([
140
                                'forms_id' => $forms->id,
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\helpdesk\Form\Forms>. 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...
141
                                'label'    => Input::get('label')[$i],
142
                                'name'     => $name,
143
                                'type'     => Input::get('type')[$i],
144
                                'required' => $require[$i],
145
                    ]);
146
                    $field_id = $field->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\helpdesk\Form\Fields>. 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...
147
                    $this->createValues($field_id, Input::get('value')[$i], null, $name);
148
                }
149
            }
150
151
            return Redirect::back()->with('success', Lang::get('lang.successfully_created_form'));
152
        } catch (Exception $ex) {
153
            dd($ex);
154
155
            return redirect()->back()->with('fails', $ex->getMessage());
156
        }
157
    }
158
159
    /**
160
     * Delete Form.
161
     *
162
     * @param type                           $id
163
     * @param \App\Model\helpdesk\Form\Forms $forms
164
     * @param type                           $field
165
     * @param type                           $help_topic
166
     *
167
     * @return type redirect
168
     */
169
    public function delete($id, Forms $forms, Fields $field, Help_topic $help_topic)
170
    {
171
        $fields = $field->where('forms_id', $id)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\Fields>? 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...
172
        $help_topics = $help_topic->where('custom_form', '=', $id)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Manage\Help_topic>? 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...
173
        foreach ($help_topics as $help_topic) {
174
            $help_topic->custom_form = null;
175
            $help_topic->save();
176
        }
177
        foreach ($fields as $field) {
178
            $field->delete();
179
        }
180
        $forms = $forms->where('id', $id)->first();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
181
        $forms->delete();
182
183
        return redirect()->back()->with('success', Lang::get('lang.form_deleted_successfully'));
184
    }
185
186 View Code Duplication
    public function edit($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
187
    {
188
        try {
189
            $forms = new Forms();
190
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
191
            $select_forms = $forms->where('id', '!=', $id)->lists('formname', 'id')->toArray();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
192
            //dd($form);
193
            if ($form) {
194
                $fields = $form->fields();
195
                //dd($fields);
196
                return view('themes.default1.admin.helpdesk.manage.form.edit', compact('form', 'fields', 'select_forms'));
197
            }
198
            throw new Exception("Sorry we can't find your request");
199
        } catch (Exception $ex) {
200
            return redirect()->back()->with('fails', $ex->getMessage());
201
        }
202
    }
203
204 View Code Duplication
    public function addChildForm($id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
205
    {
206
        try {
207
            $forms = new Forms();
208
            $form = $forms->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
209
            $select_forms = $forms->where('id', '!=', $id)->lists('formname', 'id')->toArray();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
210
            //dd($form);
211
            if ($form) {
212
                $fields = $form->fields();
213
                //dd($fields);
214
                return view('themes.default1.admin.helpdesk.manage.form.add-child', compact('form', 'fields', 'select_forms'));
215
            }
216
            throw new Exception("Sorry we can't find your request");
217
        } catch (Exception $ex) {
218
            return redirect()->back()->with('fails', $ex->getMessage());
219
        }
220
    }
221
222
    public function update($id, Request $request)
223
    {
224
        $this->validate($request, [
225
            'formname' => 'required|unique:custom_forms,formname,'.$id,
226
            'label.*'  => 'required',
227
            'name.*'   => 'required',
228
            'type.*'   => 'required',
229
        ]);
230
        try {
231
            if (!$request->input('formname')) {
232
                throw new Exception(Lang::get('lang.please_fill_form_name'));
233
            }
234
            $form = new Forms();
235
            $forms = $form->find($id);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
236
            if (!$forms) {
237
                throw new Exception('Sorry we can not find your request');
238
            }
239
            $forms->formname = Input::get('formname');
240
            $forms->save();
241
            $count = count(Input::get('name'));
242
            $field = new Fields();
243
            $fields = $field->where('forms_id', $forms->id)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\Fields>? 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...
244
            if ($fields->count($fields) > 0) {
245
                foreach ($fields as $fi) {
246
                    $fi->delete();
247
                }
248
            }
249
            //dd(Input::get('label'),Input::get('name'),Input::get('type'),Input::get('required'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% 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...
250
            for ($i = 0; $i < $count; $i++) {
251
                $name = str_slug(Input::get('name')[$i], '_');
252
                $field = $field->create([
253
                    'forms_id' => $forms->id,
254
                    'label'    => Input::get('label')[$i],
255
                    'name'     => $name,
256
                    'type'     => Input::get('type')[$i],
257
                    'required' => Input::get('required')[$i],
258
                ]);
259
                $field_id = $field->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\helpdesk\Form\Fields>. 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...
260
                $this->createValues($field_id, Input::get('value')[$i], null, $name);
261
            }
262
263
            return redirect()->back()->with('success', 'updated');
264
        } catch (Exception $ex) {
265
            dd($ex);
266
267
            return redirect()->back()->with('fails', $ex->getMessage());
268
        }
269
    }
270
271
    public function renderForm($formid)
272
    {
273
        $html = '';
274
        $forms = new Forms();
275
        $form = $forms->find($formid);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Forms>? 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...
276
        if ($form) {
277
            $fields = $form->fields();
278
            foreach ($fields as $field) {
279
                $html .= self::getForm($field);
280
            }
281
        }
282
283
        return self::requiredStyle().$html;
284
    }
285
286 View Code Duplication
    public static function getType($type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
287
    {
288
        switch ($type) {
289
            case 'select':
290
                return 'select';
291
            case 'text':
292
                return 'text';
293
            case 'email':
294
                return 'email';
295
            case 'textarea':
296
                return 'textarea';
297
            case 'select':
298
                return 'select';
299
            case 'radio':
300
                return 'radio';
301
            case 'checkbox':
302
                return 'checkbox';
303
            case 'hidden':
304
                return 'hidden';
305
            case 'password':
306
                return 'password';
307
        }
308
    }
309
310 View Code Duplication
    public static function getAttribute($type)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
311
    {
312
        switch ($type) {
313
            case 'select':
314
                return "null,['class'=>'form-control']";
315
            case 'text':
316
                return "['class'=>'form-control']";
317
            case 'email':
318
                return "['class'=>'form-control']";
319
            case 'textarea':
320
                return "['class'=>'form-control']";
321
            case 'radio':
322
                return '';
323
            case 'checkbox':
324
                return '';
325
            case 'hidden':
326
                return '';
327
            case 'password':
328
                return "['class'=>'form-control']";
329
        }
330
    }
331
332
    public static function getForm($field)
333
    {
334
        $required = false;
335
        $required_class = self::requiredClass($field->required);
336
        if ($field->required === '1') {
337
            $required = true;
338
        }
339
        $type = $field->type;
340
        $field_type = self::getType($type);
341
        switch ($field_type) {
342
            case 'select':
343
                return self::selectForm($field_type, $field, $required, $required_class);
344 View Code Duplication
            case 'text':
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...
345
                return Form::label($field->label, $field->label, ['class' => $required_class]).
346
                        Form::$field_type($field->name, null, ['class' => "form-control $field->id", 'id' => $field->id, 'required' => $required]);
347 View Code Duplication
            case 'email':
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...
348
                return Form::label($field->label, $field->label, ['class' => $required_class]).
349
                        Form::$field_type($field->name, null, ['class' => "form-control $field->id", 'id' => $field->id, 'required' => $required]);
350 View Code Duplication
            case 'password':
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...
351
                return Form::label($field->label, $field->label, ['class' => $required_class]).
352
                        Form::$field_type($field->name, ['class' => "form-control $field->id", 'id' => $field->id, 'required' => $required]);
353
354 View Code Duplication
            case 'textarea':
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...
355
                return Form::label($field->label, $field->label, ['class' => $required_class]).
356
                        Form::$field_type($field->name, null, ['class' => "form-control $field->id", 'id' => $field->id, 'required' => $required]);
357
            case 'radio':
358
                return self::radioForm($field_type, $field, $required, $required_class);
359
360
            case 'checkbox':
361
                return self::checkboxForm($field_type, $field, $required, $required_class);
362
            case 'hidden':
363
                return Form::$field_type($field->name, null, ['id' => $field->id]);
364
        }
365
    }
366
367
    public function createValues($fieldid, $values, $childid = null, $key = '')
368
    {
369
        if ($values) {
370
            $values_array = explode(',', $values);
371
            $field_values = new \App\Model\helpdesk\Form\FieldValue();
372
            $field_value = $field_values->where('field_id', $fieldid)->get();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\FieldValue>? 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...
373
            if ($field_value->count() > 0) {
374
                foreach ($field_value as $fv) {
375
                    $fv->delete();
376
                }
377
            }
378
            if (count($values_array) > 0) {
379
                foreach ($values_array as $value) {
380
                    $field_values->create([
381
                        'field_id'    => $fieldid,
382
                        'child_id'    => $childid,
383
                        'field_key'   => $key,
384
                        'field_value' => str_slug($value, '_'),
385
                    ]);
386
                }
387
            }
388
        }
389
    }
390
391
    public function addChild($fieldid, Request $request)
392
    {
393
        $ids = $request->except('_token');
394
        try {
395
            foreach ($ids as $valueid => $formid) {
396
                $field_value = new \App\Model\helpdesk\Form\FieldValue();
397
                $field_values = $field_value->where('field_id', $fieldid);
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\FieldValue>? 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...
398
                $values = $field_values->where('id', $valueid)->first();
399
                if ($values) {
400
                    //if ($formid) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
401
                    $values->child_id = $formid;
402
                    $values->save();
403
                    //}
404
                }
405
            }
406
407
            return redirect()->back()->with('success', 'Updated');
408
        } catch (Exception $ex) {
409
            return redirect()->back()->with('fails', $ex->getMessage());
410
        }
411
    }
412
413
    public function renderChild(Request $request)
414
    {
415
        self::setSession();
416
        $render = '';
417
        $value = $request->input('valueid');
418
        $fieldid = $request->input('fieldid');
419
        $field_values = new \App\Model\helpdesk\Form\FieldValue();
420
        $field_value = $field_values->where('field_id', $fieldid)->where('field_value', $value)->first();
0 ignored issues
show
Documentation Bug introduced by
The method where does not exist on object<App\Model\helpdesk\Form\FieldValue>? 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...
421
        $child = '';
422
        if ($field_value) {
423
            $child = $field_value->child_id;
424
        }
425
        if ($child !== '') {
426
            $render = $this->renderForm($child);
427
        }
428
429
        return $render;
430
    }
431
432
    public static function jqueryScript($value, $fieldid, $fieldname, $type = '', $index = '')
433
    {
434
        if ($type == 'select') {
435
            return self::jquerySelectScript($fieldid);
436
        }
437
        if ($type == 'checkbox') {
438
            return self::jqueryCheckboxScript($fieldid, $index);
439
        }
440
441
        return '<script>
442
            $("#'.str_slug($value).'").on("change", function () {
443
                var valueid = $("#'.str_slug($value).'").val();
444
                var fieldid = $("#'.$fieldid.str_slug($value).'").val();
445
                send'.$fieldid.str_slug($value).'(valueid,fieldid);
446
            });
447
            function send'.$fieldid.str_slug($value).'(valueid,fieldid) {
448
                $.ajax({
449
                    url: "'.url('forms/render/child/').'",
450
                    dataType: "html",
451
                    data: {"valueid": valueid,"fieldid": fieldid},
452
                    success: function (response) {
453
                        $("#'.$fieldname.'").html(response);
454
                    },
455
                    error: function (response) {
456
                        $("#'.$fieldname.'").html(response);
457
                    }
458
                });
459
            }
460
        </script>';
461
    }
462
463
    public static function jqueryCheckboxScript($fieldid, $index)
464
    {
465
        $session = self::getSession();
466
        $fields = new Fields();
467
        $field = $fields->find($fieldid);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Fields>? 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...
468
        if ($field) {
469
            return '<script>
470
            $("#'.$session.$index.'").on("change", function () {
471
                var valueid = $("#'.$session.$index.'").val();
472
                var fieldid = $("#f'.$session.$index.'").val();
473
                if($(this).is(":checked")) {
474
                    send'.$session.$index.'(valueid,fieldid);
475
                }else{
476
                    $("#div'.$session.'"+valueid).empty();
477
                }
478
            });
479
            function send'.$session.$index.'(valueid,fieldid) {
480
                $.ajax({
481
                    url: "'.url('forms/render/child/').'",
482
                    dataType: "html",
483
                    data: {"valueid": valueid,"fieldid": fieldid},
484
                    success: function (response) {
485
                        
486
                        $("#div'.$session.'"+valueid).html(response);
487
                        
488
                    },
489
                    error: function (response) {
490
                        $("#div'.$session.'"+valueid).html(response);
491
                    }
492
                });
493
            }
494
        </script>';
495
        }
496
    }
497
498
    public static function jquerySelectScript($fieldid)
499
    {
500
        $fields = new Fields();
501
        $field = $fields->find($fieldid);
0 ignored issues
show
Documentation Bug introduced by
The method find does not exist on object<App\Model\helpdesk\Form\Fields>? 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...
502
        $session = self::getSession();
503
        if ($field) {
504
            return '<script>
505
    $(document).ready(function () {
506
        var valueid = $(".'.$session.$fieldid.'").val();
507
       var fieldid = $("#hidden'.$session.$fieldid.'").val();
508
                send'.$session.$fieldid.'(valueid,fieldid);
509
        $(".'.$session.$fieldid.'").on("change", function () {
510
            valueid = $(".'.$session.$fieldid.'").val();
511
            var fieldid = $("#hidden'.$session.$fieldid.'").val();
512
                send'.$session.$fieldid.'(valueid,fieldid);
513
        });
514
        function send'.$session.$fieldid.'(valueid,fieldid) {
515
            $.ajax({
516
                url: "'.url('forms/render/child/').'",
517
                dataType: "html",
518
                 data: {"valueid": valueid,"fieldid": fieldid},
519
                success: function (response) {
520
                    $("#'.$session.$field->name.'").html(response);
521
                },
522
                error: function (response) {
523
                    $("#'.$session.$field->name.'").html(response);
524
                }
525
            });
526
        }
527
    });
528
529
</script>';
530
        }
531
    }
532
533
    public static function selectForm($field_type, $field, $required, $required_class)
534
    {
535
        $session = self::getSession();
536
        $script = self::jqueryScript($field_value = '', $field->id, $field->name, $field_type);
537
        $form_hidden = Form::hidden('fieldid[]', $field->id, ['id' => 'hidden'.$session.$field->id]).Form::label($field->label, $field->label, ['class' => $required_class]);
538
        $select = Form::$field_type($field->name, ['' => 'Select', 'Selects' => self::removeUnderscoreFromDB($field->values()->lists('field_value', 'field_value')->toArray())], null, ['class' => "form-control $session$field->id", 'id' => $session.$field->id, 'required' => $required]).'</br>';
539
        $html = $script.$form_hidden.$select;
540
        $response_div = '<div id='.$session.$field->name.'></div>';
541
542
        return $html.$response_div;
543
    }
544
545
    public static function radioForm($field_type, $field, $required, $required_class)
546
    {
547
        $radio = '';
548
        $html = '';
549
        $values = $field->values()->lists('field_value')->toArray();
550
        if (count($values) > 0) {
551
            foreach ($values as $field_value) {
552
                $script = self::jqueryScript($field_value, $field->id, $field->name, $field_type);
553
                $radio .= '<div>'.Form::hidden('fieldid[]', $field->id, ['id' => $field->id.str_slug($field_value)]);
554
                $radio .= Form::$field_type($field->name, $field_value, null, ['class' => "$field->id", 'id' => str_slug($field_value), 'required' => $required]).$script.'<span>   '.removeUnderscore($field_value).'</span></div>';
555
            }
556
            $html = Form::label($field->label, $field->label, ['class' => $required_class]).'</br>'.$radio.'<div id='.$field->name.'></br></div>';
557
        }
558
559
        return $html;
560
    }
561
562
    public static function checkboxForm($field_type, $field, $required, $required_class)
563
    {
564
        $session = self::getSession();
565
        $checkbox = '';
566
        $html = '';
567
        $values = $field->values()->lists('field_value')->toArray();
568
        if (count($values) > 0) {
569
            $i = 1;
570
            foreach ($values as $field_value) {
571
                $script = self::jqueryScript($field_value, $field->id, $field->name, $field_type, $i);
572
                $checkbox .= Form::hidden('fieldid[]', $field->id, ['id' => 'f'.$session.$i]);
573
                $checkbox .= Form::$field_type($field->name, $field_value, null, ['class' => "$field->id", 'id' => $session.$i, 'required' => $required]);
574
                $checkbox .= '<span>   '.removeUnderscore($field_value).'</span>';
575
                //$checkbox .="</br>";
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...
576
                $checkbox .= '<div>'.$script.'<div id=div'.$session.$field_value.'></div></div>';
577
                $i++;
578
            }
579
            $html = Form::label($field->label, $field->label, ['class' => $required_class]).'</br>'.$checkbox;
580
        }
581
582
        return $html;
583
    }
584
585
    public static function requiredStyle()
586
    {
587
        $style = "<style>
588
                .required:after {
589
                                        color: #e32 !important;
590
                                        content: ' * ' !important;
591
                                        display:inline !important;
592
                                    }
593
                    </style>";
594
595
        return $style;
596
    }
597
598
    public static function requiredClass($required)
599
    {
600
        $class = '';
601
        if ($required === '1') {
602
            $class = 'required';
603
        }
604
605
        return $class;
606
    }
607
608
    public static function setSession()
609
    {
610
        $form = self::getSession();
611
        $form++;
612
        \Session::set('fromid', $form);
613
    }
614
615
    public static function getSession()
616
    {
617
        $form = 0;
618
        if (\Session::has('fromid')) {
619
            $form = \Session::get('fromid');
620
        }
621
622
        return $form;
623
    }
624
625
    public static function removeUnderscoreFromDB($array)
626
    {
627
        $result = [];
628
        if (is_array($array) && count($array) > 0) {
629
            foreach ($array as $key => $value) {
630
                $result[$key] = removeUnderscore($value);
631
            }
632
        }
633
634
        return $result;
635
    }
636
}
637