Skip to content

Commit 9d1c9ae

Browse files
committed
Fix factory when validator has no constructor
This was affecting both v::version and v::attributes, making them impossible to use except for the concrete interface. This change allows these validators to be built using the chain.
1 parent abdc73b commit 9d1c9ae

3 files changed

Lines changed: 43 additions & 0 deletions

File tree

library/NamespacedValidatorFactory.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ private function createRule(string $ruleName, array $arguments = []): Validator
7272
throw new InvalidClassException(sprintf('"%s" must be instantiable', $name));
7373
}
7474

75+
$constructor = $reflection->getConstructor();
76+
if ($constructor === null) {
77+
return $reflection->newInstance();
78+
}
79+
7580
return $reflection->newInstanceArgs($arguments);
7681
} catch (ReflectionException) {
7782
continue;
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
/*
4+
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
5+
* SPDX-License-Identifier: MIT
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
namespace Respect\Validation\Test\Validators;
11+
12+
use Respect\Validation\Message\Template;
13+
use Respect\Validation\Validators\Core\Simple;
14+
15+
#[Template(
16+
'{{subject}} must be a no-constructor validator',
17+
'{{subject}} must not be a no-constructor validator',
18+
)]
19+
final class NoConstructor extends Simple
20+
{
21+
public function isValid(mixed $input): bool
22+
{
23+
// Accept everything for test purposes
24+
return true;
25+
}
26+
}

tests/unit/NamespacedRuleFactoryTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Respect\Validation\Test\Transformers\StubTransformer;
1919
use Respect\Validation\Test\Validators\Invalid;
2020
use Respect\Validation\Test\Validators\MyAbstractClass;
21+
use Respect\Validation\Test\Validators\NoConstructor;
2122
use Respect\Validation\Test\Validators\Stub;
2223
use Respect\Validation\Test\Validators\Valid;
2324

@@ -59,6 +60,17 @@ public function shouldDefineConstructorArgumentsWhenCreatingRule(): void
5960
self::assertSame($constructorArguments, $validator->validations);
6061
}
6162

63+
#[Test]
64+
public function shouldCreateRuleWhenNoConstructorIgnoringArguments(): void
65+
{
66+
$constructorArguments = ['a', 'b'];
67+
68+
$factory = new NamespacedValidatorFactory(new StubTransformer(), [self::TEST_RULES_NAMESPACE]);
69+
$validator = $factory->create('noConstructor', $constructorArguments);
70+
71+
self::assertInstanceOf(NoConstructor::class, $validator);
72+
}
73+
6274
#[Test]
6375
public function shouldThrowsAnExceptionWhenRuleIsInvalid(): void
6476
{

0 commit comments

Comments
 (0)