Skip to content

Commit

Permalink
Add support for Validation Rule Contract in Rule rule
Browse files Browse the repository at this point in the history
  • Loading branch information
EriBloo committed Mar 2, 2023
1 parent a00ec3f commit a8f18f8
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Attributes/Validation/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
use Illuminate\Contracts\Validation\InvokableRule as InvokableRuleContract;
use Illuminate\Contracts\Validation\Rule as RuleContract;
use Spatie\LaravelData\Support\Validation\ValidationRule;
use Illuminate\Contracts\Validation\ValidationRule as ValidationRuleContract;

#[Attribute(Attribute::TARGET_PROPERTY)]
class Rule extends ValidationRule
{
/** @var array<string|array|ValidationRule|RuleContract|InvokableRuleContract> */
/** @var array<string|array|ValidationRule|RuleContract|InvokableRuleContract|ValidationRuleContract> */
protected array $rules = [];

public function __construct(string|array|ValidationRule|RuleContract|InvokableRuleContract ...$rules)
public function __construct(string|array|ValidationRule|RuleContract|InvokableRuleContract|ValidationRuleContract ...$rules)
{
$this->rules = $rules;
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Attributes/Validation/RulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use Spatie\LaravelData\Support\Validation\ValidationRule;
use Spatie\LaravelData\Tests\Fakes\Rules\CustomInvokableLaravelRule;
use Spatie\LaravelData\Tests\Fakes\Rules\CustomLaravelRule;
use Spatie\LaravelData\Tests\Fakes\Rules\CustomLaravelValidationRule;
use Spatie\TestTime\TestTime;

beforeEach(function () {
Expand Down Expand Up @@ -88,3 +89,24 @@
'required',
]);
});

it('can use the Rule rule with validation rule contract', function () {
$rule = new Rule(
'test',
['a', 'b', 'c'],
'x|y',
new CustomLaravelValidationRule(),
new Required()
);

expect(app(RuleDenormalizer::class)->execute($rule, ValidationPath::create()))->toMatchArray([
'test',
'a',
'b',
'c',
'x',
'y',
new CustomLaravelValidationRule(),
'required',
]);
});
14 changes: 14 additions & 0 deletions tests/Fakes/Rules/CustomLaravelValidationRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Spatie\LaravelData\Tests\Fakes\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class CustomLaravelValidationRule implements ValidationRule
{

public function validate(string $attribute, mixed $value, Closure $fail): void
{
}
}

0 comments on commit a8f18f8

Please sign in to comment.