Passed
Push — master ( deef25...536b09 )
by Henri
01:22
created
examples/index.php 2 patches
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@
 block discarded – undo
24 24
     /* Transforms validation to Json format to be validated on the client if desired */
25 25
     $json = Validator::toJson($data);
26 26
 
27
-}catch(Exception $er){
27
+} catch(Exception $er){
28 28
 
29 29
     die($er->getCode().'  -  '.$er->getMessage());
30 30
 
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@  discard block
 block discarded – undo
7 7
 
8 8
 /* NOTE: in case of error an exception is thrown */
9 9
 
10
-try{
10
+try {
11 11
     /* Required format for validation */
12 12
     $data = [
13 13
         'data' => json_encode([
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
             'password' => 123456,
16 16
             'password2' => 123456,
17 17
             'phones' => [
18
-                '949164770','949164771','949164772'
18
+                '949164770', '949164771', '949164772'
19 19
             ],
20 20
             'birth' => '28/09/1996' 
21 21
         ]),
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
     /* Transforms validation to Json format to be validated on the client if desired */
30 30
     $json = Validator::toJson($data);
31 31
 
32
-}catch(Exception $er){
32
+}catch (Exception $er) {
33 33
 
34 34
     die($er->getCode().'  -  '.$er->getMessage());
35 35
 
Please login to merge, or discard this patch.
src/Validator.php 2 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,32 +95,32 @@  discard block
 block discarded – undo
95 95
         
96 96
         self::check_requireds();
97 97
 				
98
-		return true;
98
+        return true;
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
                         $function = "check_{$subkey}";
117 117
 
118 118
                         self::testMethod($function);
119 119
 
120 120
                         self::$function($keyy,$subvalue);
121
-					}
122
-				}
123
-			}
121
+                    }
122
+                }
123
+            }
124 124
         }
125 125
     }
126 126
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 
145 145
         self::existRole(self::$model);
146 146
 
147
-		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
147
+        foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
148 148
             
149 149
             $response .= ("{$field}:".json_encode(array_reverse($r))).',';
150 150
             
@@ -155,6 +155,6 @@  discard block
 block discarded – undo
155 155
         $response = str_replace('{"','',$response);
156 156
         $response = str_replace('":',':',$response);
157 157
 
158
-		return $response;
159
-	}
158
+        return $response;
159
+    }
160 160
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 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,15 +100,15 @@  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
 
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 
118 118
                         self::testMethod($function);
119 119
 
120
-                        self::$function($keyy,$subvalue);
120
+                        self::$function($keyy, $subvalue);
121 121
 					}
122 122
 				}
123 123
 			}
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 
127 127
     public static function testMethod($method)
128 128
     {
129
-        if(!method_exists(static::class, $method)){
129
+        if (!method_exists(static::class, $method)) {
130 130
             throw new Exception("{$method} não é uma validação válida.");
131 131
         }
132 132
     }
@@ -140,20 +140,20 @@  discard block
 block discarded – undo
140 140
 
141 141
         self::includeValidations();
142 142
 
143
-        self::$model = get_class( self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])) );
143
+        self::$model = get_class(self::getClass('HnrAzevedo\\Validator\\'.ucfirst($request['provider'])));
144 144
 
145 145
         self::existRole(self::$model);
146 146
 
147
-		foreach ( self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
147
+		foreach (self::$validators[self::$model]->getRules($request['role'])  as $field => $r) {
148 148
             
149 149
             $response .= ("{$field}:".json_encode(array_reverse($r))).',';
150 150
             
151 151
         }
152 152
 
153
-        $response = '{'.substr($response,0,-1).'}';
154
-        $response = str_replace(',"',',',$response);
155
-        $response = str_replace('{"','',$response);
156
-        $response = str_replace('":',':',$response);
153
+        $response = '{'.substr($response, 0, -1).'}';
154
+        $response = str_replace(',"', ',', $response);
155
+        $response = str_replace('{"', '', $response);
156
+        $response = str_replace('":', ':', $response);
157 157
 
158 158
 		return $response;
159 159
 	}
Please login to merge, or discard this patch.
src/Check.php 1 patch
Spacing   +34 added lines, -34 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 = '';
@@ -12,13 +12,13 @@  discard block
 block discarded – undo
12 12
 
13 13
     protected static function check_minlength(string $param, $value)
14 14
     {
15
-        if(self::toNext($param,$value)){    
15
+        if (self::toNext($param, $value)) {    
16 16
             
17 17
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
18 18
 
19
-            foreach($realval as $val){
20
-                if($value > strlen($val)) {
21
-                    throw new Exception("{$param} não atingiu o mínimo de caracteres esperado.",1);
19
+            foreach ($realval as $val) {
20
+                if ($value>strlen($val)) {
21
+                    throw new Exception("{$param} não atingiu o mínimo de caracteres esperado.", 1);
22 22
                 }
23 23
             }
24 24
         }       
@@ -26,21 +26,21 @@  discard block
 block discarded – undo
26 26
 
27 27
     protected static function check_requireds()
28 28
     {
29
-        if(count(self::$required) > 0){
30
-            throw new Exception('As seguintes informações não poderam ser validadas: '.implode(', ',array_keys(self::$required)).'.');
29
+        if (count(self::$required)>0) {
30
+            throw new Exception('As seguintes informações não poderam ser validadas: '.implode(', ', array_keys(self::$required)).'.');
31 31
         }
32 32
     }
33 33
 
34 34
     protected static function check_regex(string $param, $value)
35 35
     {
36
-        if(self::toNext($param,$value)){
36
+        if (self::toNext($param, $value)) {
37 37
 
38 38
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
39 39
 
40
-            foreach($realval as $val){
40
+            foreach ($realval as $val) {
41 41
 
42
-                if(!preg_match(self::$validators[self::$model]->getRules(self::$data['role'])[$param]['regex'], $val)){
43
-                    throw new Exception("{$param} inválido(a).",1);
42
+                if (!preg_match(self::$validators[self::$model]->getRules(self::$data['role'])[$param]['regex'], $val)) {
43
+                    throw new Exception("{$param} inválido(a).", 1);
44 44
                 }  
45 45
 
46 46
             }
@@ -49,27 +49,27 @@  discard block
 block discarded – undo
49 49
 
50 50
     protected static function check_mincount(string $param, $value)
51 51
     {
52
-        if(self::toNext($param,$value)){
52
+        if (self::toNext($param, $value)) {
53 53
             $array = self::testArray($param, json_decode(self::$data['data'])->$param);
54
-            if(count($array) < $value){
55
-                throw new Exception("{$param} não atingiu o mínimo esperado.",1);
54
+            if (count($array)<$value) {
55
+                throw new Exception("{$param} não atingiu o mínimo esperado.", 1);
56 56
             }
57 57
         }
58 58
     }
59 59
 
60 60
     protected static function check_maxcount(string $param, $value)
61 61
     {
62
-        if(self::toNext($param,$value)){
62
+        if (self::toNext($param, $value)) {
63 63
             $array = self::testArray($param, json_decode(self::$data['data'])->$param);
64
-            if(count($array) > $value){
65
-                throw new Exception("{$param} ultrapassou o esperado.",1);
64
+            if (count($array)>$value) {
65
+                throw new Exception("{$param} ultrapassou o esperado.", 1);
66 66
             }
67 67
         }
68 68
     }
69 69
 
70 70
     protected static function testArray(string $param, $value): ?array
71 71
     {
72
-        if(!is_array($value)){
72
+        if (!is_array($value)) {
73 73
             throw new Exception("Era esperado um informação em array para {$param}.");
74 74
         }
75 75
         return $value;
@@ -77,14 +77,14 @@  discard block
 block discarded – undo
77 77
 
78 78
     protected static function check_equals(string $param, $value)
79 79
     {
80
-        if(self::toNext($param,$value)){
80
+        if (self::toNext($param, $value)) {
81 81
 
82
-            if(!array_key_exists($param,json_decode(self::$data['data'],true))){
83
-                throw new Exception("O servidor não encontrou a informação '{$value}' para ser comparada a '{$param}'.",1);
82
+            if (!array_key_exists($param, json_decode(self::$data['data'], true))) {
83
+                throw new Exception("O servidor não encontrou a informação '{$value}' para ser comparada a '{$param}'.", 1);
84 84
             }
85 85
             
86
-            if(json_decode(self::$data['data'])->$param != json_decode(self::$data['data'],true)[$value]){
87
-                throw new Exception(ucfirst($param).' está diferente de '.ucfirst($value),1);
86
+            if (json_decode(self::$data['data'])->$param!=json_decode(self::$data['data'], true)[$value]) {
87
+                throw new Exception(ucfirst($param).' está diferente de '.ucfirst($value), 1);
88 88
             }
89 89
 
90 90
         }       
@@ -92,14 +92,14 @@  discard block
 block discarded – undo
92 92
 
93 93
     protected static function check_maxlength(string $param, $value)
94 94
     {
95
-        if(self::toNext($param,$value)){
95
+        if (self::toNext($param, $value)) {
96 96
 
97 97
             $realval = (is_array(json_decode(self::$data['data'])->$param)) ? json_decode(self::$data['data'])->$param : [json_decode(self::$data['data'])->$param];
98 98
 
99
-            foreach($realval as $val){
99
+            foreach ($realval as $val) {
100 100
 
101
-                if($value < strlen($val)) {
102
-                    throw new Exception("{$param} ultrapassou o máximo de caracteres esperado.",1);
101
+                if ($value<strlen($val)) {
102
+                    throw new Exception("{$param} ultrapassou o máximo de caracteres esperado.", 1);
103 103
                 }
104 104
             
105 105
             }
@@ -108,11 +108,11 @@  discard block
 block discarded – undo
108 108
 
109 109
     protected static function check_type(string $param, $value)
110 110
     {
111
-        if(self::toNext($param,$value)){
111
+        if (self::toNext($param, $value)) {
112 112
 
113 113
             switch ($value) {
114 114
                 case 'date':
115
-                    if(!self::validateDate(json_decode(self::$data['data'])->$param , 'd/m/Y')){
115
+                    if (!self::validateDate(json_decode(self::$data['data'])->$param, 'd/m/Y')) {
116 116
                         throw new Exception("{$param} não é uma data válida.");
117 117
                     }
118 118
                     break;
@@ -122,9 +122,9 @@  discard block
 block discarded – undo
122 122
 
123 123
     protected static function check_filter(string $param, $value)
124 124
     {
125
-        if(self::toNext($param,$value)){
125
+        if (self::toNext($param, $value)) {
126 126
 
127
-            if(!filter_var(json_decode(self::$data['data'])->$param, $value)){
127
+            if (!filter_var(json_decode(self::$data['data'])->$param, $value)) {
128 128
                 throw new Exception("{$param} não passou pela filtragem de dados.");
129 129
             }
130 130
 
@@ -134,17 +134,17 @@  discard block
 block discarded – undo
134 134
     public static function validateDate($date, $format = 'Y-m-d H:i:s')
135 135
     {
136 136
         $d = \DateTime::createFromFormat($format, $date);
137
-        return $d && $d->format($format) == $date;
137
+        return $d && $d->format($format)==$date;
138 138
     }
139 139
 
140 140
     protected static function check_required(string $param): bool
141 141
     {
142
-        return (array_key_exists('required',self::$validators[self::$model]->getRules(self::$data['role'])[$param]) && self::$validators[self::$model]->getRules(self::$data['role'])[$param]['required']);
142
+        return (array_key_exists('required', self::$validators[self::$model]->getRules(self::$data['role'])[$param]) && self::$validators[self::$model]->getRules(self::$data['role'])[$param]['required']);
143 143
     }
144 144
 
145 145
     protected static function toNext(string $param, $value)
146 146
     {
147
-        return (self::check_required($param) || strlen($value > 0));
147
+        return (self::check_required($param) || strlen($value>0));
148 148
     }
149 149
 
150 150
 }
151 151
\ No newline at end of file
Please login to merge, or discard this patch.
examples/Validations/User.php 2 patches
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -9,15 +9,15 @@
 block discarded – undo
9 9
 
10 10
         Validator::add($this, function(Rules $rules){
11 11
             $rules->setAction('login')
12
-                  //->addField('email',['minlength'=>1,'regex'=>'/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/','required'=>true])
13
-                  ->addField('email',['minlength'=>1,'filter'=>FILTER_VALIDATE_EMAIL,'required'=>true])
14
-                  ->addField('password',['minlength'=>6,'maxlength'=>20,'required'=>true])
15
-                  ->addField('password2',['equals'=>'password','required'=>true])
16
-                  ->addField('remember',['minlength'=>2,'maxlength'=>2,'required'=>false])
17
-                  ->addField('birth',['type'=>'date','required'=>true])
18
-                  ->addField('phones',['mincount'=>2,'maxcount'=>3,'required'=>true,'minlength'=>8,'maxlength'=>9]);
12
+                    //->addField('email',['minlength'=>1,'regex'=>'/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/','required'=>true])
13
+                    ->addField('email',['minlength'=>1,'filter'=>FILTER_VALIDATE_EMAIL,'required'=>true])
14
+                    ->addField('password',['minlength'=>6,'maxlength'=>20,'required'=>true])
15
+                    ->addField('password2',['equals'=>'password','required'=>true])
16
+                    ->addField('remember',['minlength'=>2,'maxlength'=>2,'required'=>false])
17
+                    ->addField('birth',['type'=>'date','required'=>true])
18
+                    ->addField('phones',['mincount'=>2,'maxcount'=>3,'required'=>true,'minlength'=>8,'maxlength'=>9]);
19 19
 
20
-			return $rules;
20
+            return $rules;
21 21
         });
22 22
 
23 23
         return $this;
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -2,20 +2,20 @@
 block discarded – undo
2 2
 
3 3
 namespace HnrAzevedo\Validator;
4 4
 
5
-Class User{
5
+Class User {
6 6
 
7 7
     public function __construct()
8 8
     {
9 9
 
10
-        Validator::add($this, function(Rules $rules){
10
+        Validator::add($this, function(Rules $rules) {
11 11
             $rules->setAction('login')
12 12
                   //->addField('email',['minlength'=>1,'regex'=>'/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/','required'=>true])
13
-                  ->addField('email',['minlength'=>1,'filter'=>FILTER_VALIDATE_EMAIL,'required'=>true])
14
-                  ->addField('password',['minlength'=>6,'maxlength'=>20,'required'=>true])
15
-                  ->addField('password2',['equals'=>'password','required'=>true])
16
-                  ->addField('remember',['minlength'=>2,'maxlength'=>2,'required'=>false])
17
-                  ->addField('birth',['type'=>'date','required'=>true])
18
-                  ->addField('phones',['mincount'=>2,'maxcount'=>3,'required'=>true,'minlength'=>8,'maxlength'=>9]);
13
+                  ->addField('email', ['minlength'=>1, 'filter'=>FILTER_VALIDATE_EMAIL, 'required'=>true])
14
+                  ->addField('password', ['minlength'=>6, 'maxlength'=>20, 'required'=>true])
15
+                  ->addField('password2', ['equals'=>'password', 'required'=>true])
16
+                  ->addField('remember', ['minlength'=>2, 'maxlength'=>2, 'required'=>false])
17
+                  ->addField('birth', ['type'=>'date', 'required'=>true])
18
+                  ->addField('phones', ['mincount'=>2, 'maxcount'=>3, 'required'=>true, 'minlength'=>8, 'maxlength'=>9]);
19 19
 
20 20
 			return $rules;
21 21
         });
Please login to merge, or discard this patch.