Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 73a717e

Browse filesBrowse files
committed
[Validator] Add createValidCallable() that returns a boolean
1 parent 22c2f1a commit 73a717e
Copy full SHA for 73a717e

File tree

3 files changed

+37
-0
lines changed
Filter options

3 files changed

+37
-0
lines changed

‎src/Symfony/Component/Validator/CHANGELOG.md

Copy file name to clipboardExpand all lines: src/Symfony/Component/Validator/CHANGELOG.md
+5Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
5.3
5+
---
6+
7+
* add `Validator::createValidClosure()` that returns true/false instead of throwing exceptions
8+
49
5.2.0
510
-----
611

‎src/Symfony/Component/Validator/Tests/ValidationTest.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Validator/Tests/ValidationTest.php
+12Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,16 @@ public function testCreateCallableInvalid()
3333
$this->expectException(ValidationFailedException::class);
3434
$validator('test');
3535
}
36+
37+
public function testCreateValidCallableValid()
38+
{
39+
$validator = Validation::createValidCallable(new Email());
40+
$this->assertTrue($validator('test@example.com'));
41+
}
42+
43+
public function testCreateValidCallableInvalid()
44+
{
45+
$validator = Validation::createValidCallable(new Email());
46+
$this->assertFalse($validator('test'));
47+
}
3648
}

‎src/Symfony/Component/Validator/Validation.php

Copy file name to clipboardExpand all lines: src/Symfony/Component/Validator/Validation.php
+20Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,26 @@ public static function createCallable($constraintOrValidator = null, Constraint
4949
};
5050
}
5151

52+
/**
53+
* Creates a callable that returns true/false instead of throwing validation exceptions.
54+
*
55+
* @param Constraint|ValidatorInterface|null $constraintOrValidator
56+
*/
57+
public static function createValidCallable($constraintOrValidator = null, Constraint ...$constraints): callable
58+
{
59+
$validator = self::createCallable(...func_get_args());
60+
61+
return static function ($value) use ($validator) {
62+
try {
63+
$validator($value);
64+
} catch (ValidationFailedException $e) {
65+
return false;
66+
}
67+
68+
return true;
69+
};
70+
}
71+
5272
/**
5373
* Creates a new validator.
5474
*

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.