Skip to content

armgit / Vvveb

Public Imported from GitHub
0

Powerful and easy to use cms to build websites, blogs or ecommerce stores.

Table columns validate method to be used for edit and add model methods validation

givanza5bdb2caf380
diff --git a/system/db/dbdriver.php b/system/db/dbdriver.php
index 39abb53..9b6f44d 100755
--- a/system/db/dbdriver.php
+++ b/system/db/dbdriver.php
@@ -116,6 +116,87 @@ class DBDriver {
}
}
+ public function validate($data, $params, $table = '', $ignoreMissing = false) {
+ $errors = [];
+
+ foreach ($params as $name => $type) {
+ if (! isset($data[$name])) {
+ if (! $ignoreMissing) {
+ $errors[] = sprintf('%s missing!', $name);
+ }
+
+ continue;
+ }
+
+ if (is_array($type)) {
+ if (isset($data[$name]) && is_array($data[$name])) {
+ //check if collection
+ if (is_numeric(key($data[$name]))) {
+ $arr = $data[$name][0] ?? [];
+ } else {
+ $arr = $data[$name];
+ }
+
+ foreach ($type as $col => $attr) {
+ //skip auto increment
+ if ((isset($attr['e']) && $attr['e'] == 'auto_increment')
+ || ($table && $col == $table . '_id')) {
+ continue;
+ }
+
+ if (! isset($arr[$col])) {
+ //skip columns that have default values
+ if (($attr['d'] === 'NULL' || $attr['d'] === NULL) && ! $ignoreMissing) {
+ $errors[] = sprintf('%s missing!', $name . '[' . $col . ']');
+ }
+ } else {
+ if (($attr['t'] == 'int' || $attr['t'] == 'decimal' || $attr['t'] == 'tinyint') && ! is_numeric($arr[$col])) {
+ $errors[] = sprintf('%s is not an integer!', $name . '[' . $col . ']');
+ }
+
+ if (isset($attr['l']) && $attr['l'] && (strlen($arr[$col]) > $attr['l'])) {
+ $errors[] = sprintf('%s is longer than %s!', $name . '[' . $col . ']', $attr['l']);
+ }
+ }
+ }
+ } else {
+ $errors[] = sprintf('%s is not an array!', $name);
+ }
+ } else {
+ switch ($type) {
+ case 'a':
+ if (! isset($data[$name]) || ! is_array($data[$name])) {
+ $errors[] = sprintf('%s is not an array!', $name);
+ } else {
+ if (substr_compare($name, '_id', -3 ,3) === 0 &&
+ ! empty($data[$name]) &&
+ ! is_numeric($data[$name][0])) {
+ $errors[] = sprintf('%s is not an integer!', $name . '[0]');
+ }
+ }
+
+ break;
+
+ case 'i':
+ if (! isset($data[$name]) || ! is_numeric($data[$name])) {
+ $errors[] = sprintf('%s is not an integer!', $name);
+ }
+
+ break;
+
+ case 's':
+ if (! isset($data[$name]) || ! is_string($data[$name])) {
+ $errors[] = sprintf('%s is not a string!', $name);
+ }
+
+ break;
+ }
+ }
+ }
+
+ return $errors;
+ }
+
/*
* Expands arrays a = ['param' => 'value', 'second' => value]; to a[param], a[second]
*/