respect-validation/tests/unit/Rules/NullableTest.php

85 lines
2.6 KiB
PHP
Raw Normal View History

2018-01-18 12:15:51 +01:00
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
2018-01-18 12:15:51 +01:00
*/
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;
2018-01-18 12:15:51 +01:00
use stdClass;
#[Group('rule')]
#[CoversClass(Nullable::class)]
final class NullableTest extends RuleTestCase
2018-01-18 12:15:51 +01:00
{
#[Test]
public function itShouldUseStandardTemplateWhenItHasNameWhenInputIsOptional(): void
2018-01-18 12:15:51 +01:00
{
$rule = new Nullable(Stub::pass(1));
2018-01-18 12:15:51 +01:00
$result = $rule->evaluate(null);
self::assertSame($rule, $result->rule);
self::assertSame(Nullable::TEMPLATE_STANDARD, $result->template);
2018-01-18 12:15:51 +01:00
}
#[Test]
public function itShouldUseNamedTemplateWhenItHasNameWhenInputIsNullable(): void
2018-01-18 12:15:51 +01:00
{
$rule = new Nullable(Stub::pass(1));
$rule->setName('foo');
2018-01-18 12:15:51 +01:00
$result = $rule->evaluate(null);
2018-01-18 12:15:51 +01:00
self::assertSame($rule, $result->rule);
self::assertSame(Nullable::TEMPLATE_NAMED, $result->template);
2018-01-18 12:15:51 +01:00
}
#[Test]
public function itShouldUseWrappedRuleToEvaluateWhenNotNullable(): void
2018-01-18 12:15:51 +01:00
{
$input = new stdClass();
$wrapped = Stub::pass(2);
$rule = new Nullable($wrapped);
self::assertEquals($wrapped->evaluate($input), $rule->evaluate($input));
2018-01-18 12:15:51 +01:00
}
/** @return iterable<string, array{Nullable, mixed}> */
public static function providerForValidInput(): iterable
2018-01-18 12:15:51 +01:00
{
yield 'null' => [new Nullable(Stub::daze()), null];
yield 'not null with passing rule' => [new Nullable(Stub::pass(1)), 42];
2018-01-18 12:15:51 +01:00
}
/** @return iterable<array{Nullable, mixed}> */
public static function providerForInvalidInput(): iterable
{
yield [new Nullable(Stub::fail(1)), ''];
yield [new Nullable(Stub::fail(1)), 1];
yield [new Nullable(Stub::fail(1)), []];
yield [new Nullable(Stub::fail(1)), ' '];
yield [new Nullable(Stub::fail(1)), 0];
yield [new Nullable(Stub::fail(1)), '0'];
yield [new Nullable(Stub::fail(1)), 0];
yield [new Nullable(Stub::fail(1)), '0.0'];
yield [new Nullable(Stub::fail(1)), false];
yield [new Nullable(Stub::fail(1)), ['']];
yield [new Nullable(Stub::fail(1)), [' ']];
yield [new Nullable(Stub::fail(1)), [0]];
yield [new Nullable(Stub::fail(1)), ['0']];
yield [new Nullable(Stub::fail(1)), [false]];
yield [new Nullable(Stub::fail(1)), [[''], [0]]];
yield [new Nullable(Stub::fail(1)), new stdClass()];
}
2018-01-18 12:15:51 +01:00
}