respect-validation/tests/unit/IdTest.php
Henrique Moody a107b8cb9f
Prevent validators from generating validatorBuilder Ids
When calling `v::validatorName()`, a `ValidatorBuilder` is instantiated
to manage the validation chain. However, users generally expect the ID
to reflect the specific validator invoked rather than the internal
builder class.

This commit updates `Id::fromValidator()` to resolve the ID from the
underlying validator when it is the sole member of the
`ValidatorBuilder`, ensuring more intuitive identification.
2026-01-26 13:57:39 +01:00

86 lines
2.1 KiB
PHP

<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\Validation;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use Respect\Validation\Test\TestCase;
use Respect\Validation\Validators\AlwaysInvalid;
#[CoversClass(Id::class)]
final class IdTest extends TestCase
{
#[Test]
public function shouldCreateInstanceWithValue(): void
{
$id = new Id('test');
self::assertSame('test', $id->value);
}
#[Test]
public function shouldCreateIdFromSimpleValidator(): void
{
$validator = new AlwaysInvalid();
$id = Id::fromValidator($validator);
self::assertSame('alwaysInvalid', $id->value);
}
#[Test]
public function shouldCreateIdFromNestedValidatorBuilder(): void
{
$validator = ValidatorBuilder::stringType();
$id = Id::fromValidator($validator);
self::assertSame('stringType', $id->value);
}
#[Test]
public function shouldCreateIdFromMultipleValidatorsInBuilder(): void
{
$validator = ValidatorBuilder::stringType()->intType();
$id = Id::fromValidator($validator);
self::assertSame('validatorBuilder', $id->value);
}
#[Test]
public function shouldAddPrefixToValue(): void
{
$id = new Id('test');
$prefixed = $id->withPrefix('my');
self::assertSame('myTest', $prefixed->value);
self::assertNotSame($id, $prefixed);
}
#[Test]
public function shouldHandleEmptyValueWithPrefix(): void
{
$id = new Id('');
$prefixed = $id->withPrefix('prefix');
self::assertSame('prefix', $prefixed->value);
}
#[Test]
public function shouldHandleMultipleRecursionInFromValidator(): void
{
$validator = ValidatorBuilder::init(ValidatorBuilder::stringType());
$id = Id::fromValidator($validator);
self::assertSame('stringType', $id->value);
}
}