WIP - create validation method for common object

This commit is contained in:
ATM john 2021-06-03 09:49:07 +02:00
parent c19f624eb5
commit a7300d01b0
3 changed files with 395 additions and 0 deletions

View File

@ -7285,6 +7285,195 @@ abstract class CommonObject
return $out;
}
/**
* Return validation test for a field
*
* @param array $val Array of properties of field to show
* @param string $key Key of attribute
* @return int >0 if OK, <0 if KO , 0 no test available.
*/
public function validateField($val, $fieldKey, $fieldValue)
{
global $langs;
if(!class_exists('Validate')){ require_once DOL_DOCUMENT_ROOT . '/core/class/validate.class.php'; }
// TODO : ask @eldy to know if need to use another error field to separate error msg
$this->error = ''; // error will be use for form error display so must be clear before
if(!isset($val[$fieldKey])){
return false;
}
$param = array();
$param['options'] = array();
$type = $val[$fieldKey]['type'];
$required = false;
if(isset($val[$fieldKey]['notnull']) && $val[$fieldKey]['notnull'] === 1){
// 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
$required = true;
}
$maxSize = 0;
//
// PREPARE Elements
//
// Convert var to be able to share same code than showOutputField of extrafields
if (preg_match('/varchar\((\d+)\)/', $type, $reg)) {
$type = 'varchar'; // convert varchar(xx) int varchar
$maxSize = $reg[1];
} elseif (preg_match('/varchar/', $type)) {
$type = 'varchar'; // convert varchar(xx) int varchar
}
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
$type = 'select';
}
if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
$type = 'link';
}
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
$param['options'] = $val['arrayofkeyval'];
}
if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
$type = 'link';
$param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
} elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
$param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4] => 'N');
$type = 'sellist';
} elseif (preg_match('/^sellist:(.*):(.*):(.*)/i', $val['type'], $reg)) {
$param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3] => 'N');
$type = 'sellist';
} elseif (preg_match('/^sellist:(.*):(.*)/i', $val['type'], $reg)) {
$param['options'] = array($reg[1].':'.$reg[2] => 'N');
$type = 'sellist';
}
//
// TEST Value
//
// Use Validate class to allow external Modules to use data validation part instead of concentrate all test here (factoring)
$validate = new Validate($this->db, $langs);
if($required && !$validate->isNotEmptyString($fieldValue)){
$this->error = $validate->error;
return -1;
}
if(!empty($maxSize) && !$validate->isMaxLength($fieldValue, $maxSize)){
$this->error = $validate->error;
return -1;
}
if (in_array($type, array('date', 'datetime', 'timestamp'))) {
if(!$validate->isTimestamp($fieldValue)){
$this->error = $validate->error;
return -1;
}
} elseif ($type == 'duration') {
// int
} elseif (in_array($type, array('double', 'real', 'price'))) {
// is numeric
} elseif ($type == 'boolean') {
// is bool
} elseif ($type == 'mail') {
if(!$validate->isEmail($fieldValue)){
$this->error = $validate->error;
return -1;
}
} elseif ($type == 'url') {
if(!$validate->isUrl($fieldValue)){
$this->error = $validate->error;
return -1;
}
} elseif ($type == 'phone') {
} elseif ($type == 'select' || $type == 'radio') {
// isset in list
if(!isset($param['options'][$fieldValue])){
}
} elseif ($type == 'sellist' || $type == 'chkbxlst') {
$param_list = array_keys($param['options']);
$InfoFieldList = explode(":", $param_list[0]);
$value_arr = explode(',', $fieldValue);
$value_arr = array_map(array($this->db, 'escape'), $value_arr);
$selectkey = "rowid";
if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
$selectkey = $InfoFieldList[2];
}
// TODO tester toute les valeur du tableau séparement
$sql = 'SELECT '.$selectkey;
$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
if ($selectkey == 'rowid' && empty($value)) {
$sql .= " WHERE ".$selectkey."=0";
} else {
$sql .= " WHERE ".$selectkey." IN ('".implode(',',$value_arr)."')";
}
dol_syslog(get_class($this).':validateField:$type=sellist', LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql) {
$num = $this->db->num_rows($resql);
if (empty($num)) {
// error value not found
$this->error = 'error msg';
return false;
} else {
return true;
}
} else {
dol_syslog(get_class($this).'::validateField error '.$this->db->lasterror(), LOG_WARNING);
return false;
}
} elseif ($type == 'link') {
// only if something to display (perf)
if (!empty($fieldValue)) {
$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
$InfoFieldList = explode(":", $param_list[0]);
$classname = $InfoFieldList[0];
$classpath = $InfoFieldList[1];
if (!empty($classpath)) {
dol_include_once($InfoFieldList[1]);
if ($classname && class_exists($classname)) {
$object = new $classname($this->db);
if($object->fetch($fieldValue)>0){
return true;
}
$this->error = 'class not found for validation';
} else {
$this->error = 'Error bad setup of extrafield';
}
return false;
} else {
$this->error = 'Error bad setup of extrafield';
return false;
}
}
else {
// TODO vérifier si requis
}
}
return 0;
}
/**
* Function to show lines of extrafields with output datas.

View File

@ -0,0 +1,194 @@
<?php
/* Copyright (C) 2021 John BOTELLA <john.botella@atm-consulting.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/core/class/validate.class.php
* \ingroup core
* \brief File for Utils class
*/
/**
* Class toolbox to validate values
*/
class Validate
{
/**
* @var DoliDb Database handler (result of a new DoliDB)
*/
public $db;
/**
* @var Translate $outputLang
*/
public $outputLang;
/**
* @var string Error string
* @see $errors
*/
public $error;
/**
* Constructor
*
* @param DoliDB $db Database handler
* @param Translate $outputLang
*/
public function __construct($db,$outputLang = false)
{
global $langs;
if ($outputLang) {
$this->outputLang = $langs;
} else {
$this->outputLang = $outputLang;
}
$outputLang->load('validate');
$this->db = $db;
}
/**
* Use to clear errors msg or other ghost vars
*/
protected function clear()
{
$this->error = '';
}
/**
* Use to clear errors msg or other ghost vars
*/
protected function setError($errMsg)
{
$this->error = '';
}
/**
* Check for e-mail validity
*
* @param string $email e-mail address to validate
* @param int $maxLength
* @return boolean Validity is ok or not
*/
public function isEmail($email, $maxLength = false)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error = $this->outputLang->trans('RequireValidEmail');
return false;
}
return true;
}
/**
* Check for price validity
*
* @param string $price Price to validate
* @return boolean Validity is ok or not
*/
public function isPrice($price)
{
if (!preg_match('/^[0-9]{1,10}(\.[0-9]{1,9})?$/ui', $price)) {
$this->error = $this->outputLang->trans('RequireValidValue');
return false;
}
return true;
}
/**
* Check for timestamp validity
*
* @param string|int $stamp timestamp to validate
* @return boolean Validity is ok or not
*/
public function isTimestamp($stamp)
{
if (!is_numeric($stamp) && (int)$stamp == $stamp) {
$this->error = $this->outputLang->trans('RequireValideDate');
return false;
}
return true;
}
/**
* Check for string max length validity
*
* @param string $string to validate
* @param int $length max length
* @return boolean Validity is ok or not
*/
public function isMaxLength($string, $length)
{
if (strlen($string) > $length) {
$this->error = $this->outputLang->trans('RequireMaxLength', $length);
return false;
}
return true;
}
/**
* Check for string not empty
*
* @param string $string to validate
* @param int $length max length
* @return boolean Validity is ok or not
*/
public function isNotEmptyString($string)
{
if (!strlen($string)) {
$this->error = $this->outputLang->trans('RequireANotEmptyValue');
return false;
}
return true;
}
/**
* Check for string min length validity
*
* @param string $string to validate
* @param int $length max length
* @return boolean Validity is ok or not
*/
public function isMinLength($string, $length)
{
if (!strlen($string) < $length) {
$this->error = $this->outputLang->trans('RequireMinLength', $length);
return false;
}
return true;
}
/**
* Check url validity
*
* @param string $url to validate
* @return boolean Validity is ok or not
*/
public function isUrl($url)
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$this->error = $this->outputLang->trans('RequireValidUrl');
return false;
}
return true;
}
}

View File

@ -0,0 +1,12 @@
# Dolibarr language file - Source file is en_US - users
RequireValidValue = Value not valid
RequireAtLeastXString = Requires at least % character(s)
RequireXStringMax = Requires % character(s) max
RequireAtLeastXDigits = Requires at least % digit(s)
RequireXDigitsMax = Requires % digit(s) max
RequireValidEmail = Email address is not valid
RequireMaxLength = Length must be less than %s chars
RequireMinLength = Length must be more than %s char(s)
RequireValidUrl = Require valid URL
RequireValideDate = Require a valid date
RequireANotEmptyValue = Is required