Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[12.x] IntroduceScopeAwareRule contract to provide relative contextual array item data to validation rules#58077

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
lucasacoutinho wants to merge1 commit intolaravel:12.x
base:12.x
Choose a base branch
Loading
fromlucasacoutinho:feat/scope-aware-rule
Draft
Show file tree
Hide file tree
Changes fromall 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
14 changes: 14 additions & 0 deletionssrc/Illuminate/Contracts/Validation/ScopeAwareRule.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
<?php

namespace Illuminate\Contracts\Validation;

interface ScopeAwareRule
{
/**
* Set the scoped data (the current array item being validated).
*
* @param array $scope
* @return $this
*/
public function setScope(array $scope);
}
30 changes: 29 additions & 1 deletionsrc/Illuminate/Validation/InvokableValidationRule.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,10 @@
use Illuminate\Contracts\Validation\ImplicitRule;
use Illuminate\Contracts\Validation\InvokableRule;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Contracts\Validation\ScopeAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidatorAwareRule;
use Illuminate\Support\Arr;
use Illuminate\Translation\CreatesPotentiallyTranslatedStrings;

class InvokableValidationRule implements Rule, ValidatorAwareRule
Expand DownExpand Up@@ -68,7 +70,8 @@ protected function __construct(ValidationRule|InvokableRule $invokable)
public static function make($invokable)
{
if ($invokable->implicit ?? false) {
return new class($invokable) extends InvokableValidationRule implements ImplicitRule {
return new class($invokable) extends InvokableValidationRule implements ImplicitRule
{
};
}

Expand All@@ -94,6 +97,10 @@ public function passes($attribute, $value)
$this->invokable->setValidator($this->validator);
}

if ($this->invokable instanceof ScopeAwareRule) {
$this->invokable->setScope($this->getScopeFromAttribute($attribute));
}

$method = $this->invokable instanceof ValidationRule
? 'validate'
: '__invoke';
Expand DownExpand Up@@ -152,4 +159,25 @@ public function setValidator($validator)

return $this;
}

protected function getScopeFromAttribute(string $attribute): array
{
$data = $this->validator->getData();
$parts = explode('.', $attribute);

$indexes = array_keys(
array_filter($parts, fn ($part) => ctype_digit((string) $part))
);

if ($indexes === []) {
return $data;
}

$scope = Arr::get(
$data,
implode('.', array_slice($parts, 0, last($indexes) + 1))
);

return is_array($scope) ? $scope : [];
}
}
278 changes: 278 additions & 0 deletionstests/Validation/ValidationScopeAwareRuleTest.php
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,278 @@
<?php

namespace Illuminate\Tests\Validation;

use Closure;
use Illuminate\Contracts\Validation\ScopeAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Translation\ArrayLoader;
use Illuminate\Translation\Translator;
use Illuminate\Validation\Validator;
use PHPUnit\Framework\TestCase;

class ValidationScopeAwareRuleTest extends TestCase
{
public function testScopeAwareRuleReceivesSiblingData()
{
$data = [
'products' => [
['price' => 100, 'discount' => 150],
['price' => 200, 'discount' => 50],
['price' => 300, 'discount' => null],
],
];

$rules = [
'products.*.price' => 'required|numeric',
'products.*.discount' => ['nullable', 'numeric', new DiscountMustBeLessThanPrice()],
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'products.0.discount' => ['Discount cannot exceed the price.'],
], $v->getMessageBag()->toArray());
}

public function testScopeAwareRulePasses()
{
$data = [
'products' => [
['price' => 100, 'discount' => 50],
['price' => 200, 'discount' => 100],
],
];

$rules = [
'products.*.price' => 'required|numeric',
'products.*.discount' => ['nullable', 'numeric', new DiscountMustBeLessThanPrice()],
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertTrue($v->passes());
}

public function testScopeAwareRuleWithDeeplyNestedWildcards()
{
$data = [
'orders' => [
[
'items' => [
['price' => 50, 'quantity' => 2, 'max_quantity' => 1],
['price' => 30, 'quantity' => 1, 'max_quantity' => 5],
],
],
[
'items' => [
['price' => 100, 'quantity' => 3, 'max_quantity' => 10],
],
],
],
];

$rules = [
'orders.*.items.*.quantity' => ['required', 'integer', new QuantityMustNotExceedMax()],
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'orders.0.items.0.quantity' => ['Quantity cannot exceed max quantity.'],
], $v->getMessageBag()->toArray());
}

public function testScopeAwareRuleWithConditionalLogic()
{
$data = [
'clients' => [
['name' => 'John', 'state' => 'CA', 'tax_id' => null],
['name' => 'Jane', 'state' => 'NY', 'tax_id' => null],
['name' => 'Bob', 'state' => 'CA', 'tax_id' => '123-456'],
],
];

$rules = [
'clients.*.name' => 'required|string',
'clients.*.state' => 'required|string',
'clients.*.tax_id' => new RequiredIfState('state', 'CA'),
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'clients.0.tax_id' => ['The clients.0.tax_id field is required when state is CA.'],
], $v->getMessageBag()->toArray());
}

public function testScopeAwareRuleCanAccessNestedSiblingData()
{
$data = [
'orders' => [
[
'type' => 'physical',
'shipping' => ['method' => 'express', 'address' => null],
],
[
'type' => 'digital',
'shipping' => ['method' => 'none', 'address' => null],
],
[
'type' => 'physical',
'shipping' => ['method' => 'standard', 'address' => '123 Main St'],
],
],
];

$rules = [
'orders.*.type' => 'required|in:physical,digital',
'orders.*.shipping.address' => new RequiredForPhysicalOrder(),
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'orders.0.shipping.address' => ['Shipping address is required for physical orders.'],
], $v->getMessageBag()->toArray());
}

public function testScopeAwareRuleWithMultipleRulesOnSameAttribute()
{
$data = [
'products' => [
['price' => 100, 'discount' => 150, 'type' => 'sale'],
['price' => 200, 'discount' => 50, 'type' => 'sale'],
['price' => 300, 'discount' => null, 'type' => 'regular'],
],
];

$rules = [
'products.*.price' => 'required|numeric',
'products.*.discount' => [
'nullable',
'numeric',
new DiscountMustBeLessThanPrice(),
],
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'products.0.discount' => ['Discount cannot exceed the price.'],
], $v->getMessageBag()->toArray());
}

public function testScopeAwareRuleWithoutWildcardReceivesFullData()
{
$data = [
'price' => 100,
'discount' => 150,
];

$rules = [
'price' => 'required|numeric',
'discount' => ['nullable', 'numeric', new DiscountMustBeLessThanPrice()],
];

$v = new Validator($this->getTranslator(), $data, $rules);

$this->assertFalse($v->passes());
$this->assertEquals([
'discount' => ['Discount cannot exceed the price.'],
], $v->getMessageBag()->toArray());
}

protected function getTranslator()
{
return new Translator(
new ArrayLoader, 'en'
);
}
}

class RequiredIfState implements ValidationRule, ScopeAwareRule
{
protected array $scope = [];

public function __construct(
protected string $field,
protected string $value
) {
}

public function setScope(array $scope): static
{
$this->scope = $scope;

return $this;
}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (($this->scope[$this->field] ?? null) === $this->value && empty($value)) {
$fail("The {$attribute} field is required when {$this->field} is {$this->value}.");
}
}
}

class RequiredForPhysicalOrder implements ValidationRule, ScopeAwareRule
{
protected array $scope = [];

public function setScope(array $scope): static
{
$this->scope = $scope;

return $this;
}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (($this->scope['type'] ?? null) === 'physical' && empty($value)) {
$fail('Shipping address is required for physical orders.');
}
}
}

class DiscountMustBeLessThanPrice implements ValidationRule, ScopeAwareRule
{
protected array $scope = [];

public function setScope(array $scope): static
{
$this->scope = $scope;

return $this;
}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value !== null && $value > ($this->scope['price'] ?? 0)) {
$fail('Discount cannot exceed the price.');
}
}
}

class QuantityMustNotExceedMax implements ValidationRule, ScopeAwareRule
{
protected array $scope = [];

public function setScope(array $scope): static
{
$this->scope = $scope;

return $this;
}

public function validate(string $attribute, mixed $value, Closure $fail): void
{
if ($value > ($this->scope['max_quantity'] ?? PHP_INT_MAX)) {
$fail('Quantity cannot exceed max quantity.');
}
}
}
Loading

[8]ページ先頭

©2009-2025 Movatter.jp