gestione gare pubbliche
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 

118 righe
3.5 KiB

<?php
/**
* Data verification class
*/
class DataVerifier {
public array $data;
public array $rules;
/**
* Generate validation rules
*/
public function __construct(array $data, array $rules)
{
$this->data = $data;
$compound_rules = [];
foreach ($rules as $rule) {
$rule_info = explode(".",$rule);
$compound_rule = [
"key" => $rule_info[0],
"type" => $rule_info[1],
"min" => $rule_info[2] ?? null,
"max" => $rule_info[3] ?? null,
"mandatory" => $rule_info[4] ?? true
];
foreach(["min","max"] as $k) {
if ($compound_rule[$k] == "null") {
$compound_rule[$k] = null;
}
}
if ($compound_rule["mandatory"] == "none") {
$compound_rule["mandatory"] = false;
} else {
$compound_rule["mandatory"] = true;
}
$compound_rules[] = $compound_rule;
}
$this->rules = $compound_rules;
}
/**
* Execute validation
* @return bool
*/
public function validate() : bool {
foreach($this->rules as $rule) {
$value = $this->data[$rule["key"]] ?? null;
if ($rule["mandatory"] && $value === null) {
return false;
}
$min = $rule["min"];
$max = $rule["max"];
if ($rule["type"] == "string") {
if (!is_string((string) $value)) {
return false;
}
if ($min !== null && strlen($value) < $min) {
return false;
}
if ($max !== null && strlen($value) > $max) {
return false;
}
}
if ($rule["type"] == "numeric") {
if (!is_numeric((int) $value)) {
return false;
}
$value = (int) $value;
if ($min !== null && $value < $min) {
return false;
}
if ($max !== null && $value > $max) {
return false;
}
}
if ($rule["type"] == "email") {
if (!is_string($value)) {
return false;
}
if ($min !== null && strlen($value) < $min) {
return false;
}
if ($max !== null && strlen($value) > $max) {
return false;
}
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
return false;
}
}
if ($rule["type"] == "array") {
if (!is_array($value)) {
return false;
}
if ($min !== null && count($value) < $min) {
return false;
}
if ($max !== null && count($value) > $max) {
return false;
}
}
if ($rule["type"] == "regex") {
if(empty($rule["min"])) {
throw new Exception("No regex specified for rule: {$rule['key']}");
}
$regex = $rule["min"];
if (empty(preg_match($regex, $value))) {
return false;
}
}
}
return true;
}
}