respect-validation/tests/feature/Issues/Issue799Test.php
Henrique Moody b5ad7aa47a
Make Validator immutable
Mutable objects can be challenging to work with in larger codebases
because different parts of a system may modify the same instance, making
it difficult to trace where and when changes occurred. This becomes
especially problematic when debugging unexpected behaviour.

By making `Validator` immutable, we ensure that adding rules via
`with()` returns a new instance rather than mutating the original, and
we use the `with()` method inside `__call()`, making every call to a
rule into a clone of the current `Validator`.

This provides several benefits:

1. Predictability: A `Validator` instance will always behave the same
   way throughout its lifetime, regardless of what other parts of the
   codebase do.

2. Safe dependency injection: Users can now confidently inject a base
   `Validator` from a DI container, knowing that any modifications made
   elsewhere will not affect their instance.

3. Easier debugging: Since validators cannot be mutated after creation,
   there's no need to track down where an unexpected rule was added.

4. Reusability: Users can create an initial `Validator` with some base
   rules and reuse it by just adding new rules to the chain without
   affecting the base `Validator`.
2026-01-02 15:45:23 +01:00

46 lines
1.6 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
use Respect\Validation\Test\Stubs\CountableStub;
$input = 'http://www.google.com/search?q=respect.github.com';
test('https://github.com/Respect/Validation/issues/799 | #1', catchAll(
fn() => v::init()
->call(
[new CountableStub(1), 'count'],
v::arrayVal()->key('scheme', v::startsWith('https')),
)
->assert($input),
fn(string $message, string $fullMessage, array $messages) => expect()
->and($message)->toBe('1 must be an array value')
->and($fullMessage)->toBe(<<<'FULL_MESSAGE'
- 1 must pass all the rules
- 1 must be an array value
- `.scheme` must be present
FULL_MESSAGE)
->and($messages)->toBe([
'__root__' => '1 must pass all the rules',
'arrayVal' => '1 must be an array value',
'scheme' => '`.scheme` must be present',
]),
));
test('https://github.com/Respect/Validation/issues/799 | #2', catchAll(
fn() => v::init()
->call(
fn($url) => parse_url((string) $url),
v::arrayVal()->key('scheme', v::startsWith('https')),
)
->assert($input),
fn(string $message, string $fullMessage, array $messages) => expect()
->and($message)->toBe('`.scheme` must start with "https"')
->and($fullMessage)->toBe('- `.scheme` must start with "https"')
->and($messages)->toBe(['scheme' => '`.scheme` must start with "https"']),
));