Themosis\Validation\ValidationBuilder::single PHP Method

single() public method

Runs a validation rule on a single passed data.
public single ( mixed $data, array $rules ) : mixed
$data mixed The given data: string, int, array, bool...
$rules array The rules to use for validation.
return mixed
    public function single($data, array $rules)
    {
        foreach ($rules as $rule) {
            // Parse $rule and check for attributes.
            $ruleProperties = $this->parseRule($rule);
            // Set rule method.
            $signature = 'validate_' . $ruleProperties['rule'];
            // Check if the datas given is an array
            // If array, parse each item and return them
            // into the array.
            if (is_array($data)) {
                // Overwrite each array value
                foreach ($data as $key => $value) {
                    // Validate the data value.
                    $data[$key] = $this->{$signature}($value, $ruleProperties['attributes']);
                }
            } else {
                // The data is a string or single value.
                $data = $this->{$signature}($data, $ruleProperties['attributes']);
            }
        }
        return $data;
    }

Usage Example

Esempio n. 1
0
 /**
  * Used to run the sanitize callbacks.
  *
  * @param mixed  $value
  * @param string $key
  * @param string $type
  *
  * @return mixed
  */
 public function sanitizeField($value, $key, $type)
 {
     $rules = $this->datas['rules.sanitize'];
     $rule = isset($rules[$key]) ? $rules[$key] : ['html'];
     $vals = [];
     // Check sanitization for infinite fields.
     if (is_array($value)) {
         foreach ($value as $k => $val) {
             if (is_array($val)) {
                 foreach ($val as $subKey => $subVal) {
                     // Check if there is a sanitize method defined for inner fields.
                     if (isset($rule[$subKey]) && !is_numeric($subKey)) {
                         $vals[$k][$subKey] = $this->validator->single($subVal, $rule[$subKey]);
                     } else {
                         // If one inner field has a rule, this one is wrong for the others because $rule is an array of array.
                         if (isset($rules[$key]) && !isset($rule[$subKey])) {
                             $vals[$k][$subKey] = $this->validator->single($subVal, ['html']);
                         } else {
                             $vals[$k][$subKey] = $this->validator->single($subVal, $rule);
                         }
                     }
                 }
             }
         }
     }
     // Return parsed array of the infinite field.
     if (!empty($vals)) {
         return $vals;
     }
     return $this->validator->single($value, $rule);
 }
All Usage Examples Of Themosis\Validation\ValidationBuilder::single