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