在我的代码中,我想从约束违例中提取消息和字段
成阵列。 PropertyAccess
为此setValue
。它适用于数组键,但不适用于对象属性。
在对象属性上使用setValue
会导致
fatal error: Uncaught Symfony\Component\PropertyAccess\Exception
\NoSuchPropertyException: Cannot write property "first_name" to an array.
Maybe you should write the property path as "[first_name]" instead?
据我了解,PropertyAccess
统一了对数组和对象的访问。为什么setValue
无法处理对象属性?
这是代码段:
$user = new User('', 'Novak', 'pnovak@examplecom');
$validator = Validation::createValidatorBuilder()->addXmlMapping('validation.xml')->getValidator();
$violations = $validator->validate($user);
$accessor = PropertyAccess::createPropertyAccessor();
$messages = [];
if (0 === count($violations)) {
echo 'validation passed';
} else {
foreach ($violations as $violation) {
// $messages[$violation->getPropertyPath()] = $violation->getMessage();
$accessor->setValue($messages,
$violation->getPropertyPath(),
$violation->getMessage());
}
dump($messages);
}