Skip to content
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
44 changes: 44 additions & 0 deletions packages/validation/src/Rules/Closure.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Tempest\Validation\Rules;

use Attribute;
use InvalidArgumentException;
use ReflectionFunction;
use Tempest\Validation\Rule;

/**
* Custom validation rule defined by a closure.
*
* The closure receives the value and must return true if it is valid, false otherwise.
*/
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final readonly class Closure implements Rule
{
private \Closure $callback;

public function __construct(
\Closure $callback,
) {
$this->callback = $callback;

$reflection = new ReflectionFunction($callback);

// Must be static
if (! $reflection->isStatic()) {
throw new InvalidArgumentException('Validation closures must be static');
}

// Must not capture variables
if ($reflection->getStaticVariables() !== []) {
throw new InvalidArgumentException('Validation closures may not capture variables.');
}
}

public function isValid(mixed $value): bool
{
return ($this->callback)($value);
}
}
45 changes: 45 additions & 0 deletions packages/validation/tests/Rules/ClosureTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace Tempest\Validation\Tests\Rules;

use PHPUnit\Framework\TestCase;
use Tempest\Validation\Rules\Closure;

/**
* @internal
*/
final class ClosureTest extends TestCase
{
public function test_closure_validation_passes(): void
{
$rule = new Closure(static fn (mixed $value): bool => str_contains((string) $value, '@'));
$this->assertTrue($rule->isValid('user@example.com'));
$this->assertTrue($rule->isValid('test@domain.org'));
}

public function test_closure_validation_fails(): void
{
$rule = new Closure(static fn (mixed $value): bool => str_contains((string) $value, '@'));

$this->assertFalse($rule->isValid('username'));
$this->assertFalse($rule->isValid('example.com'));
}

public function test_non_string_value_fails(): void
{
$rule = new Closure(static fn (mixed $value): bool => str_contains((string) $value, '@'));

$this->assertFalse($rule->isValid(12345));
$this->assertFalse($rule->isValid(null));
$this->assertFalse($rule->isValid(false));
}

public function test_static_closure_required(): void
{
$this->expectException(\InvalidArgumentException::class);

new Closure(fn (mixed $value): bool => str_contains((string) $value, '@'));
}
}