Passed
Branch master (481374)
by Henri
03:04 queued 01:44
created
examples/index.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
         'password' => 123456,
13 13
         'password2' => 123456,
14 14
         'phones' => [
15
-            '949164770','949164771','949164772'
15
+            '949164770', '949164771', '949164772'
16 16
         ],
17 17
         'birth' => '28/09/1996' 
18 18
     ]),
@@ -23,9 +23,9 @@  discard block
 block discarded – undo
23 23
 /* Checks whether the passed data is valid for the selected function */
24 24
 $valid = Validator::execute($data);
25 25
 
26
-if(!$valid){
27
-    foreach(Validator::getErrors() as $err => $message){
28
-        echo $message . PHP_EOL;
26
+if (!$valid) {
27
+    foreach (Validator::getErrors() as $err => $message) {
28
+        echo $message.PHP_EOL;
29 29
     }
30 30
 }
31 31
 
Please login to merge, or discard this patch.
src/Validator.php 3 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 
68 68
     public static function checkDatas()
69 69
     {
70
-		self::existData();
70
+        self::existData();
71 71
         self::jsonData();
72 72
         self::hasProvider();
73 73
         self::hasRole();
@@ -83,9 +83,9 @@  discard block
 block discarded – undo
83 83
 
84 84
         self::$model = get_class(self::getClass('HnrAzevedo\\Validator\\'.ucfirst(self::$data['provider'])));
85 85
 
86
-		self::existRole(self::$model);
86
+        self::existRole(self::$model);
87 87
             
88
-		foreach ( (self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
88
+        foreach ( (self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
89 89
             if(@$value['required'] === true){
90 90
                 self::$required[$key] = $value;
91 91
             }
@@ -95,24 +95,24 @@  discard block
 block discarded – undo
95 95
         
96 96
         self::check_requireds();
97 97
 				
98
-		return self::check_errors();
98
+        return self::check_errors();
99 99
     }
100 100
     
101 101
     public static function validate()
102 102
     {
103 103
         foreach ( (self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
104 104
 
105
-			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
105
+            foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
106 106
 
107
-				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
107
+                if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
108 108
                     throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
109 109
                 }
110 110
 
111
-				if($keyy===$key){
111
+                if($keyy===$key){
112 112
 
113 113
                     unset(self::$required[$key]);
114 114
 
115
-					foreach ($value as $subkey => $subvalue) {
115
+                    foreach ($value as $subkey => $subvalue) {
116 116
                         try{
117 117
                             $function = "check_{$subkey}";
118 118
                             self::testMethod($function);
@@ -121,9 +121,9 @@  discard block
 block discarded – undo
121 121
                             self::$errors[] = $exception->getMessage();
122 122
                         }
123 123
                         
124
-					}
125
-				}
126
-			}
124
+                    }
125
+                }
126
+            }
127 127
         }
128 128
     }
129 129
 
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 
153 153
         self::existRole(self::$model);
154 154
 
155
-		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
155
+        foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
156 156
             
157 157
             $response .= ("{$field}:".json_encode(array_reverse($r))).',';
158 158
             
@@ -163,6 +163,6 @@  discard block
 block discarded – undo
163 163
         $response = str_replace('{"','',$response);
164 164
         $response = str_replace('":',':',$response);
165 165
 
166
-		return $response;
167
-	}
166
+        return $response;
167
+    }
168 168
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -5,10 +5,10 @@  discard block
 block discarded – undo
5 5
 use HnrAzevedo\Validator\Rules;
6 6
 use Exception;
7 7
 
8
-Class Validator{
8
+Class Validator {
9 9
     use Check;
10 10
 
11
-    public static function add(object $model,callable $return): void
11
+    public static function add(object $model, callable $return): void
12 12
     {
13 13
         self::$model = get_class($model);
14 14
         self::$validators[self::$model] = $return($Rules = new Rules($model));
@@ -16,42 +16,42 @@  discard block
 block discarded – undo
16 16
     
17 17
     private static function existData()
18 18
     {
19
-        if(!array_key_exists('data', self::$data)){
19
+        if (!array_key_exists('data', self::$data)) {
20 20
             throw new Exception('Informações cruciais não foram recebidas.');
21 21
         }
22 22
     }
23 23
 
24 24
     private static function jsonData()
25 25
     {
26
-        if(json_decode(self::$data['data']) === null){
26
+        if (json_decode(self::$data['data'])===null) {
27 27
             throw new Exception('O servidor recebeu as informações no formato esperado.');
28 28
         }
29 29
     }
30 30
 
31 31
     private static function hasProvider()
32 32
     {
33
-        if(!array_key_exists('provider',self::$data)){
33
+        if (!array_key_exists('provider', self::$data)) {
34 34
             throw new Exception('O servidor não recebeu o ID do formulário.');
35 35
         }
36 36
     }
37 37
 
38 38
     private static function hasRole()
39 39
     {
40
-        if(!array_key_exists('role',self::$data)){
40
+        if (!array_key_exists('role', self::$data)) {
41 41
             throw new Exception('O servidor não conseguiu identificar a finalidade deste formulário.');
42 42
         }
43 43
     }
44 44
 
45 45
     private static function includeValidations()
46 46
     {
47
-        if( file_exists(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php') ){
48
-            require_once(VALIDATOR_CONFIG['path'] . ucfirst(self::$data['provider']) . '.php');
47
+        if (file_exists(VALIDATOR_CONFIG['path'].ucfirst(self::$data['provider']).'.php')) {
48
+            require_once(VALIDATOR_CONFIG['path'].ucfirst(self::$data['provider']).'.php');
49 49
         }
50 50
     }
51 51
 
52 52
     private static function getClass(string $class)
53 53
     {
54
-        if(!class_exists($class)){
54
+        if (!class_exists($class)) {
55 55
             throw new Exception("Form ID {$class} inválido.");
56 56
         }
57 57
 
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 
61 61
     private static function existRole($rules)
62 62
     {
63
-        if(empty(self::$validators[$rules]->getRules(self::$data['role']))){
63
+        if (empty(self::$validators[$rules]->getRules(self::$data['role']))) {
64 64
             throw new Exception('Não existe regras para validar este formulário.');
65 65
         }
66 66
     }
@@ -85,8 +85,8 @@  discard block
 block discarded – undo
85 85
 
86 86
 		self::existRole(self::$model);
87 87
             
88
-		foreach ( (self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
89
-            if(@$value['required'] === true){
88
+		foreach ((self::$validators[self::$model]->getRules($datas['role'])) as $key => $value) {
89
+            if (@$value['required']===true) {
90 90
                 self::$required[$key] = $value;
91 91
             }
92 92
         }
@@ -100,24 +100,24 @@  discard block
 block discarded – undo
100 100
     
101 101
     public static function validate()
102 102
     {
103
-        foreach ( (self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
103
+        foreach ((self::$validators[self::$model]->getRules(self::$data['role'])) as $key => $value) {
104 104
 
105 105
 			foreach (json_decode(self::$data['data']) as $keyy => $valuee) {
106 106
 
107
-				if(!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])) )){
107
+				if (!array_key_exists($keyy, (self::$validators[self::$model]->getRules(self::$data['role'])))) {
108 108
                     throw new Exception("O campo '{$keyy}' não é esperado para está operação.");
109 109
                 }
110 110
 
111
-				if($keyy===$key){
111
+				if ($keyy===$key) {
112 112
 
113 113
                     unset(self::$required[$key]);
114 114
 
115 115
 					foreach ($value as $subkey => $subvalue) {
116
-                        try{
116
+                        try {
117 117
                             $function = "check_{$subkey}";
118 118
                             self::testMethod($function);
119
-                            self::$function($keyy,$subvalue);
120
-                        }catch(Exception $exception){
119
+                            self::$function($keyy, $subvalue);
120
+                        }catch (Exception $exception) {
121 121
                             self::$errors[] = $exception->getMessage();
122 122
                         }
123 123
                         
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 
135 135
     public static function testMethod($method)
136 136
     {
137
-        if(!method_exists(static::class, $method)){
137
+        if (!method_exists(static::class, $method)) {
138 138
             throw new Exception("{$method} não é uma validação válida.");
139 139
         }
140 140
     }
@@ -148,20 +148,20 @@  discard block
 block discarded – undo
148 148
 
149 149
         self::includeValidations();
150 150
 
151
-        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
151
+        self::$model = get_class(self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])));
152 152
 
153 153
         self::existRole(self::$model);
154 154
 
155
-		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
155
+		foreach (self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
156 156
             
157 157
             $response .= ("{$field}:".json_encode(array_reverse($r))).',';
158 158
             
159 159
         }
160 160
 
161
-        $response = '{'.substr($response,0,-1).'}';
162
-        $response = str_replace(',"',',',$response);
163
-        $response = str_replace('{"','',$response);
164
-        $response = str_replace('":',':',$response);
161
+        $response = '{'.substr($response, 0, -1).'}';
162
+        $response = str_replace(',"', ',', $response);
163
+        $response = str_replace('{"', '', $response);
164
+        $response = str_replace('":', ':', $response);
165 165
 
166 166
 		return $response;
167 167
 	}
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@
 block discarded – undo
117 117
                             $function = "check_{$subkey}";
118 118
                             self::testMethod($function);
119 119
                             self::$function($keyy,$subvalue);
120
-                        }catch(Exception $exception){
120
+                        } catch(Exception $exception){
121 121
                             self::$errors[] = $exception->getMessage();
122 122
                         }
123 123
                         
Please login to merge, or discard this patch.
src/Check.php 1 patch
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 
5 5
 use Exception;
6 6
 
7
-Trait Check{
7
+Trait Check {
8 8
     protected static array $data = [];
9 9
     protected static array $validators = [];
10 10
     protected static string $model = '';
@@ -13,13 +13,13 @@  discard block
 block discarded – undo
13 13
 
14 14
     protected static function check_minlength(string $param, $value)
15 15
     {
16
-        if(self::toNext($param,$value)){    
16
+        if (self::toNext($param, $value)) {    
17 17
             
18 18
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
19 19
 
20
-            foreach($realval as $val){
21
-                if($value > strlen($val)) {
22
-                    throw new Exception("{$param} não atingiu o mínimo de caracteres esperado.",1);
20
+            foreach ($realval as $val) {
21
+                if ($value>strlen($val)) {
22
+                    throw new Exception("{$param} não atingiu o mínimo de caracteres esperado.", 1);
23 23
                 }
24 24
             }
25 25
         }       
@@ -27,26 +27,26 @@  discard block
 block discarded – undo
27 27
 
28 28
     protected static function check_errors(): bool
29 29
     {
30
-        return (count(self::$errors) === 0);
30
+        return (count(self::$errors)===0);
31 31
     }
32 32
 
33 33
     protected static function check_requireds()
34 34
     {
35
-        if(count(self::$required) > 0){
36
-            self::$errors[] = 'As seguintes informações não poderam ser validadas: '.implode(', ',array_keys(self::$required)).'.';
35
+        if (count(self::$required)>0) {
36
+            self::$errors[] = 'As seguintes informações não poderam ser validadas: '.implode(', ', array_keys(self::$required)).'.';
37 37
         }
38 38
     }
39 39
 
40 40
     protected static function check_regex(string $param, $value)
41 41
     {
42
-        if(self::toNext($param,$value)){
42
+        if (self::toNext($param, $value)) {
43 43
 
44 44
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
45 45
 
46
-            foreach($realval as $val){
46
+            foreach ($realval as $val) {
47 47
 
48
-                if(!preg_match(self::$validators[self::$model]->getRules(self::$data['role'])[$param]['regex'], $val)){
49
-                    throw new Exception("{$param} inválido(a).",1);
48
+                if (!preg_match(self::$validators[self::$model]->getRules(self::$data['role'])[$param]['regex'], $val)) {
49
+                    throw new Exception("{$param} inválido(a).", 1);
50 50
                 }  
51 51
 
52 52
             }
@@ -55,27 +55,27 @@  discard block
 block discarded – undo
55 55
 
56 56
     protected static function check_mincount(string $param, $value)
57 57
     {
58
-        if(self::toNext($param,$value)){
58
+        if (self::toNext($param, $value)) {
59 59
             $array = self::testArray($param, json_decode(self::$data['data'])->$param);
60
-            if(count($array) < $value){
61
-                throw new Exception("{$param} não atingiu o mínimo esperado.",1);
60
+            if (count($array)<$value) {
61
+                throw new Exception("{$param} não atingiu o mínimo esperado.", 1);
62 62
             }
63 63
         }
64 64
     }
65 65
 
66 66
     protected static function check_maxcount(string $param, $value)
67 67
     {
68
-        if(self::toNext($param,$value)){
68
+        if (self::toNext($param, $value)) {
69 69
             $array = self::testArray($param, json_decode(self::$data['data'])->$param);
70
-            if(count($array) > $value){
71
-                throw new Exception("{$param} ultrapassou o esperado.",1);
70
+            if (count($array)>$value) {
71
+                throw new Exception("{$param} ultrapassou o esperado.", 1);
72 72
             }
73 73
         }
74 74
     }
75 75
 
76 76
     protected static function testArray(string $param, $value): ?array
77 77
     {
78
-        if(!is_array($value)){
78
+        if (!is_array($value)) {
79 79
             throw new Exception("Era esperado um informação em array para {$param}.");
80 80
         }
81 81
         return $value;
@@ -83,14 +83,14 @@  discard block
 block discarded – undo
83 83
 
84 84
     protected static function check_equals(string $param, $value)
85 85
     {
86
-        if(self::toNext($param,$value)){
86
+        if (self::toNext($param, $value)) {
87 87
 
88
-            if(!array_key_exists($param,json_decode(self::$data['data'],true))){
89
-                throw new Exception("O servidor não encontrou a informação '{$value}' para ser comparada a '{$param}'.",1);
88
+            if (!array_key_exists($param, json_decode(self::$data['data'], true))) {
89
+                throw new Exception("O servidor não encontrou a informação '{$value}' para ser comparada a '{$param}'.", 1);
90 90
             }
91 91
             
92
-            if(json_decode(self::$data['data'])->$param != json_decode(self::$data['data'],true)[$value]){
93
-                throw new Exception(ucfirst($param).' está diferente de '.ucfirst($value),1);
92
+            if (json_decode(self::$data['data'])->$param!=json_decode(self::$data['data'], true)[$value]) {
93
+                throw new Exception(ucfirst($param).' está diferente de '.ucfirst($value), 1);
94 94
             }
95 95
 
96 96
         }       
@@ -98,14 +98,14 @@  discard block
 block discarded – undo
98 98
 
99 99
     protected static function check_maxlength(string $param, $value)
100 100
     {
101
-        if(self::toNext($param,$value)){
101
+        if (self::toNext($param, $value)) {
102 102
 
103 103
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
104 104
 
105
-            foreach($realval as $val){
105
+            foreach ($realval as $val) {
106 106
 
107
-                if($value < strlen($val)) {
108
-                    throw new Exception("{$param} ultrapassou o máximo de caracteres esperado.",1);
107
+                if ($value<strlen($val)) {
108
+                    throw new Exception("{$param} ultrapassou o máximo de caracteres esperado.", 1);
109 109
                 }
110 110
             
111 111
             }
@@ -114,11 +114,11 @@  discard block
 block discarded – undo
114 114
 
115 115
     protected static function check_type(string $param, $value)
116 116
     {
117
-        if(self::toNext($param,$value)){
117
+        if (self::toNext($param, $value)) {
118 118
 
119 119
             switch ($value) {
120 120
                 case 'date':
121
-                    if(!self::validateDate(json_decode(self::$data['data'])->$param , 'd/m/Y')){
121
+                    if (!self::validateDate(json_decode(self::$data['data'])->$param, 'd/m/Y')) {
122 122
                         throw new Exception("{$param} não é uma data válida.");
123 123
                     }
124 124
                     break;
@@ -128,9 +128,9 @@  discard block
 block discarded – undo
128 128
 
129 129
     protected static function check_filter(string $param, $value)
130 130
     {
131
-        if(self::toNext($param,$value)){
131
+        if (self::toNext($param, $value)) {
132 132
 
133
-            if(!filter_var(json_decode(self::$data['data'])->$param, $value)){
133
+            if (!filter_var(json_decode(self::$data['data'])->$param, $value)) {
134 134
                 throw new Exception("{$param} não passou pela filtragem de dados.");
135 135
             }
136 136
 
@@ -140,17 +140,17 @@  discard block
 block discarded – undo
140 140
     public static function validateDate($date, $format = 'Y-m-d H:i:s')
141 141
     {
142 142
         $d = \DateTime::createFromFormat($format, $date);
143
-        return $d && $d->format($format) == $date;
143
+        return $d && $d->format($format)==$date;
144 144
     }
145 145
 
146 146
     protected static function check_required(string $param): bool
147 147
     {
148
-        return (array_key_exists('required',self::$validators[self::$model]->getRules(self::$data['role'])[$param]) && self::$validators[self::$model]->getRules(self::$data['role'])[$param]['required']);
148
+        return (array_key_exists('required', self::$validators[self::$model]->getRules(self::$data['role'])[$param]) && self::$validators[self::$model]->getRules(self::$data['role'])[$param]['required']);
149 149
     }
150 150
 
151 151
     protected static function toNext(string $param, $value)
152 152
     {
153
-        return (self::check_required($param) || strlen($value > 0));
153
+        return (self::check_required($param) || strlen($value>0));
154 154
     }
155 155
 
156 156
 }
157 157
\ No newline at end of file
Please login to merge, or discard this patch.