Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Vendor\App;
- class Validator
- {
- private array $errors = [];
- public function validate(array $data, array $rules)
- {
- $valid = true;
- foreach ($rules as $item => $ruleset) {
- // $ruleset: required|email|max:5
- // $item: 'email' the key of the assos array
- $ruleset = explode('|', $ruleset);
- foreach ($ruleset as $rule) {
- // $rule: e.g. required
- $colon = strpos($rule, ':');
- $params = '';
- if ($colon != false) {
- $params = substr($rule, $colon + 1);
- $rule = substr($rule, 0, $colon);
- }
- $methodName = 'validate' . ucfirst($rule);
- $value = $data[$item] ?? null;
- if (method_exists($this, $methodName)) {
- /*
- @params
- $value: the data that meant to be verified
- $methodName: e.g validateEmail() method
- */
- $this->$methodName($item, $value, $params) OR $valid = false;
- }
- }
- }
- return $valid;
- }
- public function getErrors()
- {
- return $this->errors;
- }
- private function validateRequired($item, $value, $params)
- {
- if (empty($value)) {
- $this->errors[$item][] = 'The ' . $item . ' field is required.';
- return false;
- }
- return true;
- }
- private function validateEmail($item, $value, $params)
- {
- if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
- $this->errors[$item][] = 'The ' . $item . ' field should be a valid email address.';
- return false;
- }
- return true;
- }
- private function validateMin($item, $value, $params)
- {
- if (strlen($value) < $params) {
- $this->errors[$item][] = 'The ' . $item . ' field should have minimum length of ' . $params . '.';
- return false;
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement