respect-validation/tests/unit/Rules/LengthTest.php
Henrique Moody 9eafe52252
Refactor the Length rule
Currently, the Length rule does multiple things, yet it's limited.
Because it does many things, it's also confusing. Turning the Length
rule into a transformation allows for way more flexibility and clarity.

The syntax becomes more verbose, but I can solve that later by creating
a Transformer enables creating rules with the "length" as a prefix.

While making this change, I also removed the support for counting
objects and integers. I find that way too confusing.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-19 15:38:29 +01:00

60 lines
1.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\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Test\DataProvider as RespectDataProvider;
use Respect\Validation\Test\Rules\Stub;
use Respect\Validation\Test\TestCase;
use function count;
use function mb_strlen;
#[Group('rule')]
#[CoversClass(Length::class)]
final class LengthTest extends TestCase
{
#[Test]
#[DataProvider('providerForNonStringsNorCountable')]
public function itShouldAlwaysInvalidateNonStringsNorCountable(mixed $input): void
{
self::assertInvalidInput(new Length(Stub::any(1)), $input);
}
#[Test]
#[DataProvider('providerForStringTypes')]
public function itShouldValidateStringTypes(string $input): void
{
$wrapped = Stub::pass(1);
$rule = new Length($wrapped);
self::assertValidInput($rule, $input);
self::assertEquals(mb_strlen($input), $wrapped->inputs[0]);
}
#[Test]
#[DataProvider('providerForCountable')]
public function itShouldValidateCountable(mixed $input): void
{
$wrapped = Stub::pass(1);
$rule = new Length($wrapped);
self::assertValidInput($rule, $input);
self::assertEquals(count($input), $wrapped->inputs[0]);
}
public static function providerForNonStringsNorCountable(): RespectDataProvider
{
return self::providerForAnyValues()->without('stringType', 'countable');
}
}