我目前正在使用约束(也是自定义的)和验证器组件对实体执行一些自定义验证。我想按组获取指定的实体约束以应用正确的约束组。
我看到了 Symfony 2 的这个老问题,似乎它在 Symfony 4 中不起作用。
实体User.php
:
class User
{
private $id;
private $email;
private $origin;
...
}
文件中配置的约束validation.yaml
:
App\Domain\User:
properties:
origin:
- NotBlank: { groups: [user_create] }
- NotNull: { groups: [user_update] }
验证过程:
// Get the component by injection and gets valid metadata
// Also gets the validation groups user_* for origin field
$metadata = $this->validator->getMetadataFor(User::class);
// This returns an empty array
$constraints = $metadata->findConstraints('user_create');
// This also returns an empty array
$constraints = $metadata->findConstraints('Default');
// Empty violations because constraints are empty
$violations = $this->validator->validate($leadRequest, $constraints, 'user_create');
转储$metadata
:
ClassMetadata^ {#1551
+name: "App\Domain\User"
+defaultGroup: "User"
+members: array:11 [
"origin" => array:1 [
0 => PropertyMetadata^ {#2472
+class: "App\Domain\User"
+name: "origin"
+property: "origin"
-reflMember: array:1 [
"App\Domain\User" => ReflectionProperty {#2223
+name: "origin"
+class: "App\Domain\User"
modifiers: "private"
}
]
+constraints: array:4 [
0 => NotBlank^ {#5590
+message: "This value should not be blank."
+allowNull: false
+normalizer: null
+payload: null
+"groups": array:1 [
0 => "user_create"
]
}
1 => NotNull^ {#5567
+message: "This value should not be null."
+payload: null
+"groups": array:1 [
0 => "user_update"
]
}
...
没有关于此功能的任何文档,因此该方法可能不再有效,或者我做错了什么。
谢谢您的帮助。