respect-validation/tests/unit/Rules/KeyOptionalTest.php
Henrique Moody a3c197f600
Handle names via the Named rule
Because of how the validation engine works now [1], there's no reason to
keep adding names to each rule. Instead, create a single rule that
handles naming rules with a few other accessories. This change is not
necessarily simple, but it shrinks the `Rule` interface, and it's more
aligned with how the library works right now.

Personally, I think this API is much more straightforward than the
`setName()` method, as it's way more explicit about which rule we're
naming. Because of this change, the behaviour changed slightly, but it's
for the best.

Because of this change, I managed to remove a lot of code, but
unfortunately, it's quite a big-bang commit. It would be too complicated
to make it atomic since names are an intrinsic part of the library.

[1]: 238f2d506a
2024-12-26 23:10:19 +01:00

54 lines
1.4 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Test\Rules\Stub;
use Respect\Validation\Test\TestCase;
#[Group('rule')]
#[CoversClass(KeyOptional::class)]
final class KeyOptionalTest extends TestCase
{
#[Test]
#[DataProvider('providerForNonArrayValues')]
public function itShouldAlwaysValidateNonArrayValues(mixed $input): void
{
$rule = new KeyOptional(0, Stub::daze());
self::assertValidInput($rule, $input);
}
/** @param array<mixed> $input */
#[Test]
#[DataProvider('providerForArrayWithMissingKeys')]
public function itShouldAlwaysValidateMissingKeys(int|string $key, array $input): void
{
$rule = new KeyOptional($key, Stub::daze());
self::assertValidInput($rule, $input);
}
/** @param array<mixed> $input */
#[Test]
#[DataProvider('providerForArrayWithExistingKeys')]
public function itShouldValidateExistingKeysWithWrappedRule(int|string $key, array $input): void
{
$wrapped = Stub::pass(1);
$rule = new KeyOptional($key, $wrapped);
$rule->evaluate($input);
self::assertEquals($wrapped->inputs, [$input[$key]]);
}
}