Skip to content

Commit 404a5db

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 404a5db

3 files changed

Lines changed: 42 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: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@ public function shouldDefineConstructorArgumentsWhenCreatingRule(): void
5959
self::assertSame($constructorArguments, $validator->validations);
6060
}
6161

62+
#[Test]
63+
public function shouldCreateRuleWhenNoConstructorIgnoringArguments(): void
64+
{
65+
$constructorArguments = ['a', 'b'];
66+
67+
$factory = new NamespacedValidatorFactory(new StubTransformer(), [self::TEST_RULES_NAMESPACE]);
68+
$validator = $factory->create('noConstructor', $constructorArguments);
69+
70+
self::assertInstanceOf(\Respect\Validation\Test\Validators\NoConstructor::class, $validator);
71+
}
72+
6273
#[Test]
6374
public function shouldThrowsAnExceptionWhenRuleIsInvalid(): void
6475
{

0 commit comments

Comments
 (0)