hcportal-dev/Aiko/Libs/Validator.php

110 lines
2.5 KiB
PHP

<?php
namespace Aiko;
use Exception;
class Validator
{
private $request = [];
private $rules = [];
private $errorBag = [];
public $valid = [];
public function __construct($request, $rules = [])
{
$this->rules = $rules;
if (!is_array($request) && is_object($request)) {
$this->request = json_decode(json_encode($request), true);
} else {
$this->request = $request;
}
}
/**
* @param string $paramKey
* @param \Closure($value, $params): string|null $validatorFn
*/
public function addRule($paramKey, $validatorFn, $messages = [])
{
array_push($this->rules, new ValidationRule($this->request, $paramKey, $validatorFn, $messages));
return $this;
}
public function fails()
{
return count($this->errorBag) > 0;
}
public function safe($key = null)
{
if (is_null($key)) {
return $this->valid;
}
if (isset($this->valid[$key])) {
return $this->valid[$key];
}
return null;
}
public function all()
{
return $this->request;
}
public function only($keys = [])
{
$request = [];
foreach ($keys as $key) {
if (array_key_exists($key, $this->request)) {
$request[$key] = $this->request[$key];
}
}
return $request;
}
public function errors()
{
return $this->errorBag;
}
public function validate($throw = false)
{
/** @var ValidationRule $rule */
foreach ($this->rules as $rule) {
if (!$rule->validate()) {
if ($throw) {
throw new ValidatorException($rule->key, $rule->errorBag);
}
array_push($this->errorBag, $rule->errorBag);
continue;
}
$this->valid[$rule->key] = $rule->getParamValue();
}
}
}
class ValidatorException extends Exception
{
private $data;
// Redefine the exception so message isn't optional
public function __construct($message, $data = [], $previous = null)
{
parent::__construct($message, 0, $previous);
$this->data = $data;
}
// custom string representation of object
public function __toString()
{
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function getData()
{
return $this->data;
}
}