3 namespace Wikimedia\ParamValidator
;
7 use UnexpectedValueException
;
10 * Error reporting for ParamValidator
15 class ValidationException
extends UnexpectedValueException
{
21 protected $paramValue;
27 protected $failureCode;
29 /** @var (string|int|string[])[] */
30 protected $failureData;
33 * @param string $name Parameter name being validated
34 * @param mixed $value Value of the parameter
35 * @param array $settings Settings array being used for validation
36 * @param string $code Failure code. See getFailureCode() for requirements.
37 * @param (string|int|string[])[] $data Data for the failure code.
38 * See getFailureData() for requirements.
39 * @param Throwable|Exception|null $previous Previous exception causing this failure
41 public function __construct( $name, $value, $settings, $code, $data, $previous = null ) {
42 parent
::__construct( self
::formatMessage( $name, $code, $data ), 0, $previous );
44 $this->paramName
= $name;
45 $this->paramValue
= $value;
46 $this->settings
= $settings;
47 $this->failureCode
= $code;
48 $this->failureData
= $data;
52 * Make a simple English message for the exception
58 private static function formatMessage( $name, $code, $data ) {
59 $ret = "Validation of `$name` failed: $code";
60 foreach ( $data as $k => $v ) {
61 if ( is_array( $v ) ) {
62 $v = implode( ', ', $v );
70 * Fetch the parameter name that failed validation
73 public function getParamName() {
74 return $this->paramName
;
78 * Fetch the parameter value that failed validation
81 public function getParamValue() {
82 return $this->paramValue
;
86 * Fetch the settings array that failed validation
89 public function getSettings() {
90 return $this->settings
;
94 * Fetch the validation failure code
96 * A validation failure code is a reasonably short string matching the regex
97 * `/^[a-z][a-z0-9-]*$/`.
99 * Users are encouraged to use this with a suitable i18n mechanism rather
100 * than relying on the limited English text returned by getMessage().
104 public function getFailureCode() {
105 return $this->failureCode
;
109 * Fetch the validation failure data
111 * This returns additional data relevant to the particular failure code.
113 * Keys in the array are short ASCII strings. Values are strings or
114 * integers, or arrays of strings intended to be displayed as a
115 * comma-separated list. For any particular code the same keys are always
116 * returned in the same order, making it safe to use array_values() and
117 * access them positionally if that is desired.
119 * For example, the data for a hypothetical "integer-out-of-range" code
120 * might have data `[ 'min' => 0, 'max' => 100 ]` indicating the range of
123 * @return (string|int|string[])[]
125 public function getFailureData() {
126 return $this->failureData
;