respect-validation/tests/unit/Rules/NullOrTest.php
Henrique Moody d7dc0f2b4e
Refactor the "NullOr" rule and related classes
This commit will rename the "Nullable" rule to "NullOr" while soft
deprecating the old name. It should work the same as the previous one
but with a different name. It will also prefix the result ID, allowing
more message customization.

While working on it, I realized that the prefix "nullOr" had a typo,
and it was using "nullOf" instead. I fixed that, too.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-26 01:55:50 +01:00

85 lines
2.6 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\Group;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Test\Rules\Stub;
use Respect\Validation\Test\RuleTestCase;
use stdClass;
#[Group('rule')]
#[CoversClass(NullOr::class)]
final class NullOrTest extends RuleTestCase
{
#[Test]
public function itShouldUseStandardTemplateWhenItHasNameWhenInputIsOptional(): void
{
$rule = new NullOr(Stub::pass(1));
$result = $rule->evaluate(null);
self::assertSame($rule, $result->rule);
self::assertSame(NullOr::TEMPLATE_STANDARD, $result->template);
}
#[Test]
public function itShouldUseNamedTemplateWhenItHasNameWhenInputIsNullable(): void
{
$rule = new NullOr(Stub::pass(1));
$rule->setName('foo');
$result = $rule->evaluate(null);
self::assertSame($rule, $result->rule);
self::assertSame(NullOr::TEMPLATE_NAMED, $result->template);
}
#[Test]
public function itShouldUseWrappedRuleToEvaluateWhenNotNullable(): void
{
$input = new stdClass();
$wrapped = Stub::pass(2);
$rule = new NullOr($wrapped);
self::assertEquals($wrapped->evaluate($input)->withPrefixedId('nullOr'), $rule->evaluate($input));
}
/** @return iterable<string, array{NullOr, mixed}> */
public static function providerForValidInput(): iterable
{
yield 'null' => [new NullOr(Stub::daze()), null];
yield 'not null with passing rule' => [new NullOr(Stub::pass(1)), 42];
}
/** @return iterable<array{NullOr, mixed}> */
public static function providerForInvalidInput(): iterable
{
yield [new NullOr(Stub::fail(1)), ''];
yield [new NullOr(Stub::fail(1)), 1];
yield [new NullOr(Stub::fail(1)), []];
yield [new NullOr(Stub::fail(1)), ' '];
yield [new NullOr(Stub::fail(1)), 0];
yield [new NullOr(Stub::fail(1)), '0'];
yield [new NullOr(Stub::fail(1)), 0];
yield [new NullOr(Stub::fail(1)), '0.0'];
yield [new NullOr(Stub::fail(1)), false];
yield [new NullOr(Stub::fail(1)), ['']];
yield [new NullOr(Stub::fail(1)), [' ']];
yield [new NullOr(Stub::fail(1)), [0]];
yield [new NullOr(Stub::fail(1)), ['0']];
yield [new NullOr(Stub::fail(1)), [false]];
yield [new NullOr(Stub::fail(1)), [[''], [0]]];
yield [new NullOr(Stub::fail(1)), new stdClass()];
}
}