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 // FIXME pass some revision ts or we get the wrong type of access! 53 $access = AccessTable::byTableName($table, $pageid, time()); 54 $validation = $access->getValidator($data[$table]); 55 if (!$validation->validate()) { 56 $valid = false; 57 $errors = array_merge($errors, $validation->getErrors()); 58 } else { 59 if ($validation->hasChanges()) { 60 $tosave[] = $validation; 61 } 62 } 63 } 64 if ($valid) return $tosave; 65 return false; 66 } 67 68 /** 69 * Validate the data. This will clean the data according to type! 70 * 71 * @return bool 72 */ 73 public function validate() 74 { 75 $result = true; 76 foreach ($this->access->getSchema()->getColumns() as $col) { 77 $label = $col->getType()->getLabel(); 78 $result = $result && $this->validateValue($col, $this->data[$label]); 79 } 80 return $result; 81 } 82 83 /** 84 * Check if the data changed (selects current data) 85 * 86 * @return bool 87 */ 88 public function hasChanges() 89 { 90 $olddata = $this->access->getDataArray(); 91 return ($olddata != $this->data); 92 } 93 94 /** 95 * @return AccessTable 96 */ 97 public function getAccessTable() 98 { 99 return $this->access; 100 } 101 102 /** 103 * Access the data after it has been cleand in the validation process 104 * 105 * @return array 106 */ 107 public function getCleanData() 108 { 109 return $this->data; 110 } 111 112 /** 113 * Saves the data 114 * 115 * This saves no matter what. You have to chcek validation results and changes on your own! 116 * 117 * @param int $ts the timestamp to use when saving the data 118 * @return bool 119 */ 120 public function saveData($ts = 0) 121 { 122 $this->access->setTimestamp($ts); 123 return $this->access->saveData($this->data); 124 } 125} 126