1<?php 2/* 3** Zabbix 4** Copyright (C) 2001-2021 Zabbix SIA 5** 6** This program is free software; you can redistribute it and/or modify 7** it under the terms of the GNU General Public License as published by 8** the Free Software Foundation; either version 2 of the License, or 9** (at your option) any later version. 10** 11** This program is distributed in the hope that it will be useful, 12** but WITHOUT ANY WARRANTY; without even the implied warranty of 13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14** GNU General Public License for more details. 15** 16** You should have received a copy of the GNU General Public License 17** along with this program; if not, write to the Free Software 18** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 19**/ 20 21 22class CStringValidator extends CValidator { 23 24 /** 25 * If set to false, the string cannot be empty. 26 * 27 * @var bool 28 */ 29 public $empty = false; 30 31 /** 32 * Maximum string length. 33 * 34 * @var int 35 */ 36 public $maxLength; 37 38 /** 39 * Regex to match the string against. 40 * 41 * @var string 42 */ 43 public $regex; 44 45 /** 46 * Error message if the string is empty. 47 * 48 * @var string 49 */ 50 public $messageEmpty; 51 52 /** 53 * Error message if the string is too long. 54 * 55 * @var string 56 */ 57 public $messageMaxLength; 58 59 /** 60 * Error message if the string doesn't match the regex. 61 * 62 * @var string 63 */ 64 public $messageRegex; 65 66 /** 67 * Error message if not a string, integer or decimal is provided 68 * 69 * @var string 70 */ 71 public $messageInvalid; 72 73 /** 74 * Checks if the given string is: 75 * - empty 76 * - not too long 77 * - matches a certain regex 78 * 79 * @param string $value 80 * 81 * @return bool 82 */ 83 public function validate($value) { 84 if (!(is_string($value) || is_numeric($value))) { 85 $this->error($this->messageInvalid, $this->stringify($value)); 86 87 return false; 88 } 89 90 if (zbx_empty($value)) { 91 if ($this->empty) { 92 return true; 93 } 94 else { 95 $this->error($this->messageEmpty); 96 97 return false; 98 } 99 } 100 101 if ($this->maxLength && mb_strlen($value) > $this->maxLength) { 102 $this->error($this->messageMaxLength, $value, $this->maxLength); 103 104 return false; 105 } 106 107 if ($this->regex && !zbx_empty($value) && !preg_match($this->regex, $value)) { 108 $this->error($this->messageRegex, $value); 109 110 return false; 111 } 112 113 return true; 114 } 115} 116