Passed
Push — master ( 284e72...816a06 )
by Iman
04:12
created

FormValidator::parseValidationRules()   C

Complexity

Conditions 8
Paths 5

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 23
nc 5
nop 2
dl 0
loc 39
rs 5.3846
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\controllers;
4
5
use crocodicstudio\crudbooster\helpers\DbInspector;
6
use Illuminate\Support\Facades\Schema;
7
use Illuminate\Support\Facades\Validator;
8
use Illuminate\Support\Facades\Request;
9
use crocodicstudio\crudbooster\helpers\CRUDBooster;
10
11
class FormValidator
12
{
13
    private $table;
14
15
    private $ctrl;
16
17
    public function validate($id = null, $form, $ctrl)
18
    {
19
        $this->ctrl = $ctrl;
20
        $this->table = $ctrl->table;
21
        $rules = $this->getRules($id, $form);
22
23
        $validator = Validator::make(request()->all(), $rules);
24
25
        if (! $validator->fails()) {
26
            return null;
27
        }
28
29
        $this->sendFailedValidationResponse($validator);
30
    }
31
32
    /**
33
     * @param $id
34
     * @param $form
35
     * @return mixed
36
     */
37
    private function getRules($id, $form)
38
    {
39
        $cmpPath = CbComponentsPath();
40
        $rules = [];
41
        foreach ($form as $formInput) {
42
            $name = $formInput['name'];
43
            if (! $name) {
44
                continue;
45
            }
46
47
            $ai = [];
48
            if ($formInput['required'] && ! Request::hasFile($name)) {
49
                $ai[] = 'required';
50
            }
51
52
            $hookValidationPath = $cmpPath.$formInput['type'].DIRECTORY_SEPARATOR.'hookInputValidation.php';
53
            if (file_exists($hookValidationPath)) {
54
                require_once($hookValidationPath);
55
            }
56
            unset($hookValidationPath);
57
58
            if (@$formInput['validation']) {
59
                $rules[$name] = $this->parseValidationRules($id, $formInput);
60
            } else {
61
                $rules[$name] = implode('|', $ai);
62
            }
63
        }
64
65
        return $rules;
66
    }
67
68
    /**
69
     * @param $id
70
     * @param $formInput
71
     * @return array
72
     */
73
    private function parseValidationRules($id, $formInput)
74
    {
75
        $exp = explode('|', $formInput['validation']);
76
77
        $uniqueRules = array_filter($exp, function($item){
78
            return starts_with($item, 'unique');
79
        });
80
81
        foreach ($uniqueRules as &$validationItem) {
82
            $parseUnique = explode(',', str_replace('unique:', '', $validationItem));
83
            $uniqueTable = ($parseUnique[0]) ?: $this->table;
84
            $uniqueColumn = ($parseUnique[1]) ?: $formInput['name'];
85
            $uniqueIgnoreId = ($parseUnique[2]) ?: (($id) ?: '');
86
87
            //Make sure table name
88
            $uniqueTable = CRUDBooster::parseSqlTable($uniqueTable)['table'];
89
90
            //Rebuild unique rule
91
            $uniqueRebuild = [];
92
            $uniqueRebuild[] = $uniqueTable;
93
            $uniqueRebuild[] = $uniqueColumn;
94
95
            if ($uniqueIgnoreId) {
96
                $uniqueRebuild[] = $uniqueIgnoreId;
97
            } else {
98
                $uniqueRebuild[] = 'NULL';
99
            }
100
101
            //Check whether deleted_at exists or not
102
            if (Schema::hasColumn($uniqueTable, 'deleted_at')) {
103
                $uniqueRebuild[] = DbInspector::findPK($uniqueTable);
104
                $uniqueRebuild[] = 'deleted_at';
105
                $uniqueRebuild[] = 'NULL';
106
            }
107
            $uniqueRebuild = array_filter($uniqueRebuild);
108
            $validationItem = 'unique:'.implode(',', $uniqueRebuild);
109
        }
110
111
        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...
112
    }
113
114
    /**
115
     * @param $validator
116
     */
117
    private function sendFailedValidationResponse($validator)
118
    {
119
        $message = $validator->messages();
120
        $msg = [
121
            'message' => cbTrans('alert_validation_error', ['error' => implode(', ', $message->all())]),
122
            'message_type' => 'warning',
123
        ];
124
125
        if (Request::ajax()) {
126
            $resp = response()->json($msg);
0 ignored issues
show
Bug introduced by
The method json() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

126
            $resp = response()->/** @scrutinizer ignore-call */ json($msg);
Loading history...
127
            sendAndTerminate($resp);
128
        }
129
        sendAndTerminate(redirect()->back()->with("errors", $message)->with($msg)->withnput());
130
    }
131
}