Description
Version: symfony/validator 3.1.6, PHP 7.0.7
Background: I've been using the validator component for APIs for a long time (without forms though). One of the problems was that apart from the descriptive violation messages I wanted to return a fixed error name that can be handled by the application on the other end. I've achieved that by extending the base constraints and overriding the error messages (which means no descriptive message). I could live with that, waited for better times.
I noticed that the ConstraintViolation includes the ::getCode
method now! Perfect for my little APIs. The code seems to be an UUID and each of the constraints includes a mapping to nice error names. UUIDs are usable but they are not the best UX for the end-programmer :).
The meat: The easiest way to get the error name would be to use Constraint::getErrorName
method. This is where the problem is - in some cases the ConstraintViolation
has the wrong Constraint
attached. From the first look - it's the last tested constraint, not the one that failed.
I am aware that I am assuming the the ConstraintViolationInterface
is actually a ConstraintViolation
but IMO it's fair to assume when I'm using Symfony's validator component. Also the ConstraintViolation::getConstraint
and Constraint::getErrorName
methods are public so I am (I hope) not relying on some internal implementation details.
I am attaching a testcase for further illustration:
https://gist.github.com/pinkeen/7a3b6688efc3c493fc16807ac89d3a3f