@@ -116,6 +116,87 @@ public function filter($data, $columns, $addMissingDefaults = false) {
116
116
}
117
117
}
118
118
119
+ public function validate ($ data , $ params , $ table = '' , $ ignoreMissing = false ) {
120
+ $ errors = [];
121
+
122
+ foreach ($ params as $ name => $ type ) {
123
+ if (! isset ($ data [$ name ])) {
124
+ if (! $ ignoreMissing ) {
125
+ $ errors [] = sprintf ('%s missing! ' , $ name );
126
+ }
127
+
128
+ continue ;
129
+ }
130
+
131
+ if (is_array ($ type )) {
132
+ if (isset ($ data [$ name ]) && is_array ($ data [$ name ])) {
133
+ //check if collection
134
+ if (is_numeric (key ($ data [$ name ]))) {
135
+ $ arr = $ data [$ name ][0 ] ?? [];
136
+ } else {
137
+ $ arr = $ data [$ name ];
138
+ }
139
+
140
+ foreach ($ type as $ col => $ attr ) {
141
+ //skip auto increment
142
+ if ((isset ($ attr ['e ' ]) && $ attr ['e ' ] == 'auto_increment ' )
143
+ || ($ table && $ col == $ table . '_id ' )) {
144
+ continue ;
145
+ }
146
+
147
+ if (! isset ($ arr [$ col ])) {
148
+ //skip columns that have default values
149
+ if (($ attr ['d ' ] === 'NULL ' || $ attr ['d ' ] === NULL ) && ! $ ignoreMissing ) {
150
+ $ errors [] = sprintf ('%s missing! ' , $ name . '[ ' . $ col . '] ' );
151
+ }
152
+ } else {
153
+ if (($ attr ['t ' ] == 'int ' || $ attr ['t ' ] == 'decimal ' || $ attr ['t ' ] == 'tinyint ' ) && ! is_numeric ($ arr [$ col ])) {
154
+ $ errors [] = sprintf ('%s is not an integer! ' , $ name . '[ ' . $ col . '] ' );
155
+ }
156
+
157
+ if (isset ($ attr ['l ' ]) && $ attr ['l ' ] && (strlen ($ arr [$ col ]) > $ attr ['l ' ])) {
158
+ $ errors [] = sprintf ('%s is longer than %s! ' , $ name . '[ ' . $ col . '] ' , $ attr ['l ' ]);
159
+ }
160
+ }
161
+ }
162
+ } else {
163
+ $ errors [] = sprintf ('%s is not an array! ' , $ name );
164
+ }
165
+ } else {
166
+ switch ($ type ) {
167
+ case 'a ' :
168
+ if (! isset ($ data [$ name ]) || ! is_array ($ data [$ name ])) {
169
+ $ errors [] = sprintf ('%s is not an array! ' , $ name );
170
+ } else {
171
+ if (substr_compare ($ name , '_id ' , -3 ,3 ) === 0 &&
172
+ ! empty ($ data [$ name ]) &&
173
+ ! is_numeric ($ data [$ name ][0 ])) {
174
+ $ errors [] = sprintf ('%s is not an integer! ' , $ name . '[0] ' );
175
+ }
176
+ }
177
+
178
+ break ;
179
+
180
+ case 'i ' :
181
+ if (! isset ($ data [$ name ]) || ! is_numeric ($ data [$ name ])) {
182
+ $ errors [] = sprintf ('%s is not an integer! ' , $ name );
183
+ }
184
+
185
+ break ;
186
+
187
+ case 's ' :
188
+ if (! isset ($ data [$ name ]) || ! is_string ($ data [$ name ])) {
189
+ $ errors [] = sprintf ('%s is not a string! ' , $ name );
190
+ }
191
+
192
+ break ;
193
+ }
194
+ }
195
+ }
196
+
197
+ return $ errors ;
198
+ }
199
+
119
200
/*
120
201
* Expands arrays a = ['param' => 'value', 'second' => value]; to a[param], a[second]
121
202
*/
0 commit comments