Advertisement
freeman701

Validator Class

Dec 4th, 2021
1,193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.13 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Vendor\App;
  4.  
  5. class Validator
  6. {
  7.     private array $errors = [];
  8.  
  9.     public function validate(array $data, array $rules)
  10.     {
  11.         $valid = true;
  12.  
  13.         foreach ($rules as $item => $ruleset) {
  14.             // $ruleset: required|email|max:5
  15.             // $item: 'email' the key of the assos array
  16.             $ruleset = explode('|', $ruleset);
  17.  
  18.             foreach ($ruleset as $rule) {
  19.                 // $rule: e.g. required
  20.                 $colon = strpos($rule, ':');
  21.  
  22.                 $params = '';
  23.                 if ($colon != false) {
  24.                     $params = substr($rule, $colon + 1);
  25.                     $rule = substr($rule, 0, $colon);
  26.                 }
  27.  
  28.                 $methodName = 'validate' . ucfirst($rule);
  29.                 $value = $data[$item] ?? null;
  30.                 if (method_exists($this, $methodName)) {
  31.                     /*
  32.                      @params
  33.                      $value: the data that meant to be verified
  34.                      $methodName: e.g validateEmail() method
  35.                     */
  36.                     $this->$methodName($item, $value, $params) OR $valid = false;
  37.                 }
  38.             }
  39.         }
  40.  
  41.         return $valid;
  42.     }
  43.  
  44.     public function getErrors()
  45.     {
  46.         return $this->errors;
  47.     }
  48.  
  49.     private function validateRequired($item, $value, $params)
  50.     {
  51.         if (empty($value)) {
  52.             $this->errors[$item][] = 'The ' . $item . ' field is required.';
  53.             return false;
  54.         }
  55.  
  56.         return true;
  57.     }
  58.  
  59.     private function validateEmail($item, $value, $params)
  60.     {
  61.         if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
  62.             $this->errors[$item][] = 'The ' . $item . ' field should be a valid email address.';
  63.             return false;
  64.         }
  65.  
  66.         return true;
  67.        
  68.     }
  69.  
  70.     private function validateMin($item, $value, $params)
  71.     {
  72.         if (strlen($value) < $params) {
  73.             $this->errors[$item][] = 'The ' . $item . ' field should have minimum length of ' . $params . '.';
  74.             return false;
  75.         }
  76.  
  77.         return true;
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement