1<?php 2 3namespace dokuwiki\plugin\struct\meta; 4 5use dokuwiki\plugin\struct\types\AbstractBaseType; 6 7/** 8 * Validator to validate a single value 9 */ 10class ValueValidator 11{ 12 13 /** @var \helper_plugin_struct_db */ 14 protected $hlp; 15 16 /** @var array list of validation errors */ 17 protected $errors; 18 19 /** 20 * ValueValidator constructor. 21 */ 22 public function __construct() 23 { 24 $this->hlp = plugin_load('helper', 'struct_db'); 25 $this->errors = array(); 26 } 27 28 /** 29 * Validate a single value 30 * 31 * @param Column $col the column of that value 32 * @param mixed &$rawvalue the value, will be fixed according to the type 33 * @return bool 34 */ 35 public function validateValue(Column $col, &$rawvalue) 36 { 37 // fix multi value types 38 $type = $col->getType(); 39 $trans = $type->getTranslatedLabel(); 40 if ($type->isMulti() && !is_array($rawvalue)) { 41 $rawvalue = $type->splitValues($rawvalue); 42 } 43 // strip empty fields from multi vals 44 if (is_array($rawvalue)) { 45 $rawvalue = array_filter($rawvalue, array($this, 'filter')); 46 $rawvalue = array_values($rawvalue); // reset the array keys 47 } 48 49 // validate data 50 return $this->validateField($type, $trans, $rawvalue); 51 } 52 53 /** 54 * The errors that occured during validation 55 * 56 * @return string[] already translated error messages 57 */ 58 public function getErrors() 59 { 60 return $this->errors; 61 } 62 63 /** 64 * Validate the given data for a single field 65 * 66 * Catches the Validation exceptions and transforms them into proper error messages. 67 * 68 * Blank values are not validated and always pass 69 * 70 * @param AbstractBaseType $type 71 * @param string $label 72 * @param array|string|int &$data may be modified by the validation function 73 * @return bool true if the data validates, otherwise false 74 */ 75 protected function validateField(AbstractBaseType $type, $label, &$data) 76 { 77 $prefix = sprintf($this->hlp->getLang('validation_prefix'), $label); 78 79 $ok = true; 80 if (is_array($data)) { 81 foreach ($data as &$value) { 82 if (!blank($value)) { 83 try { 84 $value = $type->validate($value); 85 } catch (ValidationException $e) { 86 $this->errors[] = $prefix . $e->getMessage(); 87 $ok = false; 88 } 89 } 90 } 91 return $ok; 92 } 93 94 if (!blank($data)) { 95 try { 96 $data = $type->validate($data); 97 } catch (ValidationException $e) { 98 $this->errors[] = $prefix . $e->getMessage(); 99 $ok = false; 100 } 101 } 102 return $ok; 103 } 104 105 /** 106 * Simple filter to remove blank values 107 * 108 * @param string $val 109 * @return bool 110 */ 111 public function filter($val) 112 { 113 return !blank($val); 114 } 115} 116