1<?php 2 3namespace dokuwiki\plugin\struct\meta; 4 5/** 6 * Validate the data for a whole schema 7 * 8 * Should be aquired through AccessDataTable::getValidator() 9 */ 10class AccessDataValidator extends ValueValidator 11{ 12 13 /** @var AccessTable */ 14 protected $access; 15 16 /** @var array */ 17 protected $data; 18 19 /** 20 * ValidationResult constructor. 21 * @param AccessTable $access 22 * @param array $data the data to validate (and save) 23 */ 24 public function __construct(AccessTable $access, $data) 25 { 26 parent::__construct(); 27 $this->access = $access; 28 $this->data = $data; 29 } 30 31 /** 32 * Validate the given data 33 * 34 * checks for assignments 35 * validates 36 * returns changed data only 37 * 38 * @param array $data array('schema' => ( 'fieldlabel' => 'value', ...)) 39 * @param string $pageid 40 * @param string[] $errors validation errors 41 * @return AccessDataValidator[]|bool savable data or false on validation error 42 */ 43 public static function validateDataForPage($data, $pageid, &$errors) 44 { 45 $tosave = array(); 46 $valid = true; 47 $errors = array(); 48 49 $assignments = Assignments::getInstance(); 50 $tables = $assignments->getPageAssignments($pageid); 51 foreach ($tables as $table) { 52 $access = AccessTable::getPageAccess($table, $pageid); 53 $validation = $access->getValidator($data[$table]); 54 if (!$validation->validate()) { 55 $valid = false; 56 $errors = array_merge($errors, $validation->getErrors()); 57 } else { 58 if ($validation->hasChanges()) { 59 $tosave[] = $validation; 60 } 61 } 62 } 63 if ($valid) return $tosave; 64 return false; 65 } 66 67 /** 68 * Validate the data. This will clean the data according to type! 69 * 70 * @return bool 71 */ 72 public function validate() 73 { 74 $result = true; 75 foreach ($this->access->getSchema()->getColumns() as $col) { 76 $label = $col->getType()->getLabel(); 77 $result = $result && $this->validateValue($col, $this->data[$label]); 78 } 79 return $result; 80 } 81 82 /** 83 * Check if the data changed (selects current data) 84 * 85 * @return bool 86 */ 87 public function hasChanges() 88 { 89 $olddata = $this->access->getDataArray(); 90 return ($olddata != $this->data); 91 } 92 93 /** 94 * @return AccessTable 95 */ 96 public function getAccessTable() 97 { 98 return $this->access; 99 } 100 101 /** 102 * Access the data after it has been cleand in the validation process 103 * 104 * @return array 105 */ 106 public function getCleanData() 107 { 108 return $this->data; 109 } 110 111 /** 112 * Saves the data 113 * 114 * This saves no matter what. You have to chcek validation results and changes on your own! 115 * 116 * @param int $ts the timestamp to use when saving the data 117 * @return bool 118 */ 119 public function saveData($ts = 0) 120 { 121 $this->access->setTimestamp($ts); 122 return $this->access->saveData($this->data); 123 } 124} 125