diff options
Diffstat (limited to 'src/Validator.php')
-rw-r--r-- | src/Validator.php | 94 |
1 files changed, 94 insertions, 0 deletions
diff --git a/src/Validator.php b/src/Validator.php new file mode 100644 index 0000000..33cdf34 --- /dev/null +++ b/src/Validator.php @@ -0,0 +1,94 @@ +<?php + +namespace FlatFileForms; + +class Validator +{ + public function __construct( + private string $formPath + ) + {} + + public function validateRequest(array $fields): array + { + /**@var Utilities $utilities*/ + global $utilities; + + $result = []; + $hasInvalidFields = false; + + $fields = $this->validateFields($fields); + + if ($utilities->isPagedFieldSet($fields)) { + // remove surplus field values from response + $fields = array_map(function ($page) { + return array_map(function ($field) { + return array_intersect_key($field, array_flip([ + 'is_valid', + ])); + }, $page); + }, $fields); + + $flattened = array_merge(...array_values($fields)); + $hasInvalidFields = in_array(false, array_column($flattened, 'is_valid')); + } else { + // remove surplus field values from response + $fields = array_map(function ($field) { + return array_intersect_key($field, array_flip([ + 'is_valid', + ])); + }, $fields); + + $hasInvalidFields = in_array(false, array_column($fields, 'is_valid')); + } + + $result['fields'] = $fields; + + if ($hasInvalidFields) { + $result['error'] = 'invalid fields'; + } + + return $result; + } + + public function validateFields(array $fields): array + { + /**@var Utilities $utilities*/ + global $utilities; + + if ($utilities->isPagedFieldSet($fields)) { + foreach ($fields as $pageKey => &$pageFields) { + foreach ($pageFields as $key => &$field) { + $field = $this->validateSingleField($field); + } + } + } else { + foreach ($fields as $key => &$field) { + $field = $this->validateSingleField($field); + } + } + + return $fields; + } + + public function validateSingleField(array $field): array + { + $value = $_POST[$field['name']] ?? ''; + $field['is_valid'] = true; + + if (isset($field['required']) && empty($value)) { + $field['is_valid'] = false; + } + + if (isset($field['validation']['pattern']) && preg_match_all('/' . $field['validation']['pattern'] . '/', $value) === 0) { + $field['is_valid'] = false; + } + + $validationFunctionName = 'validate_' . basename($this->formPath) . '_' . $field['name']; + if (function_exists($validationFunctionName)) { + $field = call_user_func($validationFunctionName, $field, $value); + } + + return $field; + } +} |