Skip to content

Commit 94d121f

Browse files
committed
Add a CallableValidator
1 parent 48233b0 commit 94d121f

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Validator\Tests\Validator;
13+
14+
use PHPUnit\Framework\TestCase;
15+
use Symfony\Component\Validator\Constraints\Email;
16+
use Symfony\Component\Validator\Constraints\Length;
17+
use Symfony\Component\Validator\Exception\LogicException;
18+
use Symfony\Component\Validator\Validator\CallableValidator;
19+
20+
/**
21+
* @author Jan Vernieuwe <jan.vernieuwe@phpro.be>
22+
*/
23+
class CallableValidatorTest extends TestCase
24+
{
25+
public function testValidate()
26+
{
27+
$validator = new CallableValidator([new Length(['min' => 10]), new Email()]);
28+
$this->assertEquals('test@example.com', $validator('test@example.com'));
29+
$this->expectException(LogicException::class);
30+
$validator('test');
31+
}
32+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the Symfony package.
5+
*
6+
* (c) Fabien Potencier <fabien@symfony.com>
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Symfony\Component\Validator\Validator;
13+
14+
use Symfony\Component\Validator\Constraint;
15+
use Symfony\Component\Validator\Validation;
16+
use Symfony\Component\Validator\Exception\LogicException;
17+
18+
/**
19+
* Class that enables usage of the validators in console questions
20+
*
21+
* @author Jan Vernieuwe <jan.vernieuwe@phpro.be>
22+
*/
23+
class CallableValidator
24+
{
25+
/**
26+
* @var Constraint[]
27+
*/
28+
private $constraints;
29+
30+
/**
31+
* @var ValidatorInterface
32+
*/
33+
private $validator;
34+
35+
/**
36+
* CallableValidator constructor.
37+
*
38+
* @param Constraint[] $constraints
39+
*/
40+
public function __construct(array $constraints)
41+
{
42+
$this->constraints = $constraints;
43+
$this->validator = Validation::createValidator();
44+
}
45+
46+
/**
47+
* @param string $value
48+
*
49+
* @return string|null
50+
* @throws LogicException
51+
*/
52+
public function __invoke(string $value = null): string
53+
{
54+
$violations = $this->validator->validate($value, $this->constraints);
55+
if (0 !== $violations->count()) {
56+
throw new LogicException((string)$violations);
57+
}
58+
59+
return $value;
60+
}
61+
}

0 commit comments

Comments
 (0)