Passed
Push — master ( d63a45...8016ac )
by Iman
09:10
created

FormValidator::getRules()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 10
nop 2
dl 0
loc 29
rs 8.5226
c 0
b 0
f 0
1
<?php
2
3
namespace Crocodicstudio\Crudbooster\Controllers;
4
5
use Crocodicstudio\Crudbooster\Helpers\DbInspector;
6
use Crocodicstudio\Crudbooster\Helpers\CRUDBooster;
7
8
class FormValidator
9
{
10
    private $table;
11
12
    private $ctrl;
13
14
    public function validate($id = null, $form, $ctrl)
15
    {
16
        $this->ctrl = $ctrl;
17
        $this->table = $ctrl->table;
18
        $rules = $this->getRules($id, $form);
19
20
        $validator = \Validator::make(request()->all(), $rules);
21
22
        if (! $validator->fails()) {
23
            return null;
24
        }
25
26
        $this->sendFailedValidationResponse($validator);
27
    }
28
29
    /**
30
     * @param $id
31
     * @param $form
32
     * @return mixed
33
     */
34
    private function getRules($id, $form)
35
    {
36
        $cmpPath = CbComponentsPath();
37
        $rules = [];
38
        foreach ($form as $formInput) {
39
            $name = $formInput['name'];
40
            if (! $name) {
41
                continue;
42
            }
43
44
            $ai = [];
45
            if ($formInput['required'] && ! \Request::hasFile($name)) {
46
                $ai[] = 'required';
47
            }
48
49
            $hookValidationPath = $cmpPath.$formInput['type'].DIRECTORY_SEPARATOR.'hookInputValidation.php';
50
            if (file_exists($hookValidationPath)) {
51
                require_once($hookValidationPath);
52
            }
53
            unset($hookValidationPath);
54
55
            if (isset($formInput['validation'])) {
56
                $rules[$name] = $this->parseValidationRules($id, $formInput['validation'], $formInput['name']);
57
            } else {
58
                $rules[$name] = implode('|', $ai);
59
            }
60
        }
61
62
        return $rules;
63
    }
64
65
    /**
66
     * @param $id
67
     * @param $rules
68
     * @param $name
69
     * @return array
70
     * @throws \Exception
71
     */
72
    private function parseValidationRules($id, $rules, $name)
73
    {
74
        if (is_string($rules)) {
75
            $exp = explode('|', $rules);
76
        } elseif(is_array($rules)) {
77
            $exp = $rules;
78
        }
79
80
        $uniqueRules = array_filter($exp, function($item){
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exp does not seem to be defined for all execution paths leading up to this point.
Loading history...
81
            return starts_with($item, 'unique');
82
        });
83
84
        foreach ($uniqueRules as &$validationItem) {
85
            $parseUnique = explode(',', str_replace('unique:', '', $validationItem));
86
            $uniqueTable = ($parseUnique[0]) ?: $this->table;
87
            $uniqueColumn = ($parseUnique[1]) ?: $name;
88
            $uniqueIgnoreId = ($parseUnique[2]) ?: (($id) ?: '');
89
90
            //Make sure table name
91
            $uniqueTable = CRUDBooster::parseSqlTable($uniqueTable)['table'];
92
93
            //Rebuild unique rule
94
            $uniqueRebuild = [];
95
            $uniqueRebuild[] = $uniqueTable;
96
            $uniqueRebuild[] = $uniqueColumn;
97
98
            if ($uniqueIgnoreId) {
99
                $uniqueRebuild[] = $uniqueIgnoreId;
100
            } else {
101
                $uniqueRebuild[] = 'NULL';
102
            }
103
104
            //Check whether deleted_at exists or not
105
            if (\Schema::hasColumn($uniqueTable, 'deleted_at')) {
106
                $uniqueRebuild[] = DbInspector::findPK($uniqueTable);
107
                $uniqueRebuild[] = 'deleted_at';
108
                $uniqueRebuild[] = 'NULL';
109
            }
110
            $uniqueRebuild = array_filter($uniqueRebuild);
111
            $validationItem = 'unique:'.implode(',', $uniqueRebuild);
112
        }
113
114
        return implode('|', $exp);
0 ignored issues
show
Bug Best Practice introduced by
The expression return implode('|', $exp) returns the type string which is incompatible with the documented return type array.
Loading history...
115
    }
116
117
    /**
118
     * @param $validator
119
     */
120
    private function sendFailedValidationResponse($validator)
121
    {
122
        $message = $validator->messages();
123
        $msg = [
124
            'message' => cbTrans('alert_validation_error', ['error' => implode(', ', $message->all())]),
125
            'message_type' => 'warning',
126
        ];
127
128
        if (\Request::ajax()) {
129
            respondWith()->json($msg);
130
        }
131
        respondWith(redirect()->back()->with("errors", $message)->with($msg)->withInput());
132
    }
133
}