Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support rule required_if #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/ValidationRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,19 @@ public static function make(string $name, Closure $closure, array $args = []): s
return static::$pool[$hash] ?? (static::$pool[$hash] = new static($name, $closure, $args));
}

public string $rule;

protected function __construct(
public string $name,
public Closure $closure,
public array $args = []
) {
$this->rule = $this->name;
}

public function setRule(string $rule): static
{
$this->rule = $rule;
return $this;
}
}
92 changes: 61 additions & 31 deletions src/ValidationRuleset.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace KK\Validation;

use Closure;
use Hyperf\Validation\ValidationRuleParser;
use InvalidArgumentException;
use JetBrains\PhpStorm\Pure;
use SplFileInfo;
Expand Down Expand Up @@ -41,6 +42,7 @@ class ValidationRuleset

protected const PRIORITY_MAP = [
'required' => 50,
'required_if' => 50,
'numeric' => 100,
'integer' => 100,
'string' => 100,
Expand Down Expand Up @@ -111,6 +113,14 @@ protected function __construct(array $ruleMap)
$rules[] = ValidationRule::make('required', static::getClosure('validateRequired' . static::fetchTypedRule($ruleMap)));
}
break;
case 'required_if':
if (count($ruleArgs) !== 2) {
throw new InvalidArgumentException("Rule '{$rule}' require 2 parameter");
}
$name = "{$rule}:{$ruleArgs[0]},{$ruleArgs[1]}";
$ruleArgs[] = 'validateRequired' . static::fetchTypedRule($ruleMap);
$rules[] = ValidationRule::make($name, static::getClosure('validateRequiredIf'), $ruleArgs)->setRule($rule);
break;
case 'nullable':
$flags |= static::FLAG_NULLABLE;
break;
Expand Down Expand Up @@ -199,7 +209,7 @@ public function getRules(): array
/**
* @return string[] Error attribute names
*/
public function check(mixed $data): array
public function check(mixed $data, array $attributes = [], ?string $ruleName = null): array
{
if (($this->flags & static::FLAG_NULLABLE) && $data === null) {
return [];
Expand All @@ -208,8 +218,12 @@ public function check(mixed $data): array
$errors = [];

foreach ($this->rules as $rule) {
if ($ruleName && $ruleName !== $rule->rule) {
continue;
}

$closure = $rule->closure;
$valid = $closure($data, ...$rule->args);
$valid = $closure($data, $attributes, ...$rule->args);
if (!$valid) {
$errors[] = $rule->name;
/* Always bail here, for example:
Expand Down Expand Up @@ -322,7 +336,7 @@ protected static function getClosure(string $method): Closure
(static::$closureCache[$method] = Closure::fromCallable([static::class, $method]));
}

protected static function validateRequired(mixed $value): bool
protected static function validateRequired(mixed $value, array $attributes): bool
{
if (is_null($value)) {
return false;
Expand All @@ -340,22 +354,36 @@ protected static function validateRequired(mixed $value): bool
return true;
}

protected static function validateRequiredString(mixed $value): bool
protected static function validateRequiredIf(mixed $value, array $attributes, string $key, mixed $keyValue, string $validator): bool
{
if (array_key_exists($key, $attributes)) {
if ($attributes[$key] == $keyValue) {
if ($value === null) {
return false;
}
return self::$validator($value, $attributes);
}
}

return true;
}

protected static function validateRequiredString(mixed $value, array $attributes): bool
{
return $value !== '' && !ctype_space($value);
}

protected static function validateRequiredArray(array $value): bool
protected static function validateRequiredArray(array $value, array $attributes): bool
{
return count($value) !== 0;
}

protected static function validateRequiredFile(SplFileInfo $value): bool
protected static function validateRequiredFile(SplFileInfo $value, array $attributes): bool
{
return $value->getPath() !== '';
}

protected static function validateNumeric(mixed &$value): bool
protected static function validateNumeric(mixed &$value, array $attributes): bool
{
if (!is_numeric($value)) {
return false;
Expand All @@ -364,7 +392,7 @@ protected static function validateNumeric(mixed &$value): bool
return true;
}

protected static function validateInteger(mixed &$value): bool
protected static function validateInteger(mixed &$value, array $attributes): bool
{
if (filter_var($value, FILTER_VALIDATE_INT) === false) {
return false;
Expand All @@ -373,17 +401,17 @@ protected static function validateInteger(mixed &$value): bool
return true;
}

protected static function validateString(mixed $value): bool
protected static function validateString(mixed $value, array $attributes): bool
{
return is_string($value);
}

protected static function validateArray(mixed $value): bool
protected static function validateArray(mixed $value, array $attributes): bool
{
return is_array($value);
}

protected static function getLength(mixed $value): int
protected static function getLength(mixed $value, array $attributes): int
{
if (is_numeric($value)) {
return $value + 0;
Expand All @@ -400,49 +428,50 @@ protected static function getLength(mixed $value): int
return mb_strlen((string) $value);
}

protected static function validateMin(mixed $value, int|float $min): bool
protected static function validateMin(mixed $value, array $attributes, int|float $min): bool
{
// TODO: file min support b, kb, mb, gb ...
return static::getLength($value) >= $min;
return static::getLength($value, $attributes) >= $min;
}

protected static function validateMax(mixed $value, int|float $max): bool
protected static function validateMax(mixed $value, array $attributes, int|float $max): bool
{
// TODO: file max support b, kb, mb, gb ...
return static::getLength($value) <= $max;
return static::getLength($value, $attributes) <= $max;
}

protected static function validateMinInteger(int $value, int|float $min): bool
protected static function validateMinInteger(int $value, array $attributes, int|float $min): bool
{
return $value >= $min;
}

protected static function validateMaxInteger(int $value, int|float $max): bool
protected static function validateMaxInteger(int $value, array $attributes, int|float $max): bool
{
return $value <= $max;
}

protected static function validateMinNumeric(int|float $value, int|float $min): bool
protected static function validateMinNumeric(int|float $value, array $attributes, int|float $min): bool
{
return $value >= $min;
}

protected static function validateMaxNumeric(int|float $value, int|float $max): bool
protected static function validateMaxNumeric(int|float $value, array $attributes, int|float $max): bool
{
return $value <= $max;
}

protected static function validateMinString(string $value, int|float $min): bool
protected static function validateMinString(string $value, array $attributes, int|float $min): bool
{
return mb_strlen($value) >= $min;
}

protected static function validateMaxString(string $value, int|float $max): bool
protected static function validateMaxString(string $value, array $attributes, int|float $max): bool
{
return mb_strlen($value) <= $max;
}

#[Pure] protected static function validateInList(mixed $value, array $list): bool
#[Pure]
protected static function validateInList(mixed $value, array $attributes, array $list): bool
{
if (!is_array($value)) {
return in_array((string) $value, $list, true);
Expand All @@ -451,7 +480,7 @@ protected static function validateMaxString(string $value, int|float $max): bool
}
}

protected static function validateInListArray(array $value, array $list): bool
protected static function validateInListArray(array $value, array $attributes, array $list): bool
{
foreach ($value as $item) {
if (is_array($item)) {
Expand All @@ -464,7 +493,8 @@ protected static function validateInListArray(array $value, array $list): bool
return true;
}

#[Pure] protected static function validateInMap(mixed $value, array $map): bool
#[Pure]
protected static function validateInMap(mixed $value, array $attributes, array $map): bool
{
if (!is_array($value)) {
return $map[(string) $value] ?? false;
Expand All @@ -473,7 +503,7 @@ protected static function validateInListArray(array $value, array $list): bool
}
}

protected static function validateInMapArray(array $value, array $map): bool
protected static function validateInMapArray(array $value, array $attributes, array $map): bool
{
foreach ($value as $item) {
if (is_array($item)) {
Expand All @@ -486,32 +516,32 @@ protected static function validateInMapArray(array $value, array $map): bool
return true;
}

public static function validateAlpha(string $value): bool
public static function validateAlpha(string $value, array $attributes): bool
{
return preg_match('/^[\pL\pM]+$/u', $value);
}

public static function validateAlphaNum(string $value): bool
public static function validateAlphaNum(string $value, array $attributes): bool
{
return preg_match('/^[\pL\pM\pN]+$/u', $value) > 0;
}

public static function validateAlphaDash(string $value): bool
public static function validateAlphaDash(string $value, array $attributes): bool
{
return preg_match('/^[\pL\pM\pN_-]+$/u', $value) > 0;
}

public static function validateIP(string $value): bool
public static function validateIP(string $value, array $attributes): bool
{
return filter_var($value, FILTER_VALIDATE_IP) !== false;
}

public static function validateIPV4(string $value): bool
public static function validateIPV4(string $value, array $attributes): bool
{
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
}

public static function validateIPV6(string $value): bool
public static function validateIPV6(string $value, array $attributes): bool
{
return filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false;
}
Expand Down
8 changes: 7 additions & 1 deletion src/Validator.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,16 @@ protected function validRecursive(array $data, array $validationPairs, array $cu
$this->recordError($currentPatternPart, 'required');
$invalid = true;
}

if($errors = $ruleset->check(null, $data, 'required_if')){
$this->recordErrors($currentPatternPart, $errors);
$invalid = true;
}

continue;
}
$value = $data[$currentPatternPart];
$errors = $ruleset->check($value);
$errors = $ruleset->check($value, $data);
if ($errors) {
$this->recordErrors($currentPatternPart, $errors);
$invalid = true;
Expand Down
12 changes: 12 additions & 0 deletions tests/HyperfValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ public function testFails()
$this->assertFalse($validator->fails());
}

public function testRequiredIf()
{
$validator = $this->makeValidator(['type' => 1], ['id' => 'required_if:type,1', 'type' => 'required']);
$this->assertTrue($validator->fails());
}

public function testMax()
{
$validator = $this->makeValidator(['id' => 256], ['id' => 'max:255']);
$this->assertTrue($validator->fails());
}

public function testGetMessageBag()
{
$data = [['id' => 256], ['id' => 'required|integer|max:255']];
Expand Down
Loading