hcportal-dev/Aiko/Libs/ValidatorRule.php

102 lines
2.4 KiB
PHP

<?php
namespace Aiko;
use ReflectionClass;
class ValidationRule
{
/**
* @var string
*/
public $key;
/**
* @var \Closure|string
*/
public $action;
/**
* @var array
*/
public $paramBag = [];
/**
* @var array
*/
public $errorBag = [];
/**
* @var array
*/
public $messages = [];
public function __construct($paramBag, $key, $action, $messages = [])
{
$this->key = $key;
$this->action = $action;
$this->paramBag = $paramBag;
$this->messages = $messages;
}
public function validate()
{
$param = $this->getParamValue();
if (is_callable($this->action)) {
$fn = $this->action;
$message = $fn($param, $this->paramBag);
if ($message !== null) {
$this->addError($message);
return false;
}
} else if (is_string($this->action)) {
$repo = new ValidatorRuleCollection();
$ref = new ReflectionClass($repo);
$method = $this->action;
if (strpos($this->action, '|') != false) {
$exp = explode('|', $this->action);
$method = $exp[0];
}
try {
$refMethod = $ref->getMethod($method);
$result = $refMethod->invokeArgs(new ValidatorRuleCollection(), [$this->key, $this->action, $param, $this->paramBag]);
if (!is_null($result)) {
$this->addError($result);
return false;
}
return true;
} catch (\ReflectionException $e) {
return false;
}
} else {
// defensive action
return false;
}
return true;
}
public function parseMessage($messageKey)
{
if (array_key_exists($messageKey, $this->messages)) {
return $this->messages[$messageKey];
}
return $messageKey;
}
public function addError($message = null)
{
$this->errorBag = [
'key' => $this->key,
'message' => is_null($message) ? "{$this->key} cant be empty" : $this->parseMessage($message)
];
}
public function getParamValue()
{
if (array_key_exists($this->key, $this->paramBag)) {
return $this->paramBag[$this->key];
}
return null;
}
}