3 namespace Wikimedia\ParamValidator\TypeDef
;
5 use Wikimedia\ParamValidator\Callbacks
;
6 use Wikimedia\ParamValidator\ParamValidator
;
7 use Wikimedia\ParamValidator\TypeDef
;
8 use Wikimedia\ParamValidator\ValidationException
;
11 * Type definition for string types
13 * The result from validate() is a PHP string.
15 * ValidationException codes:
16 * - 'missingparam': The parameter is the empty string (and that's not allowed). No data.
18 * Additional codes may be generated when using certain PARAM constants. See
19 * the constants' documentation for details.
23 class StringDef
extends TypeDef
{
26 * (integer) Maximum length of a string in bytes.
28 * ValidationException codes:
29 * - 'maxbytes': The string is too long. Data:
30 * - 'maxbytes': The maximum number of bytes allowed
31 * - 'maxchars': The maximum number of characters allowed
33 const PARAM_MAX_BYTES
= 'param-max-bytes';
36 * (integer) Maximum length of a string in characters (Unicode codepoints).
38 * The string is assumed to be encoded as UTF-8.
40 * ValidationException codes:
41 * - 'maxchars': The string is too long. Data:
42 * - 'maxbytes': The maximum number of bytes allowed
43 * - 'maxchars': The maximum number of characters allowed
45 const PARAM_MAX_CHARS
= 'param-max-chars';
47 protected $allowEmptyWhenRequired = false;
50 * @param Callbacks $callbacks
51 * @param array $options Options:
52 * - allowEmptyWhenRequired: (bool) Whether to reject the empty string when PARAM_REQUIRED.
55 public function __construct( Callbacks
$callbacks, array $options = [] ) {
56 parent
::__construct( $callbacks );
58 $this->allowEmptyWhenRequired
= !empty( $options['allowEmptyWhenRequired'] );
61 public function validate( $name, $value, array $settings, array $options ) {
62 if ( !$this->allowEmptyWhenRequired
&& $value === '' &&
63 !empty( $settings[ParamValidator
::PARAM_REQUIRED
] )
65 throw new ValidationException( $name, $value, $settings, 'missingparam', [] );
68 if ( isset( $settings[self
::PARAM_MAX_BYTES
] )
69 && strlen( $value ) > $settings[self
::PARAM_MAX_BYTES
]
71 throw new ValidationException( $name, $value, $settings, 'maxbytes', [
72 'maxbytes' => $settings[self
::PARAM_MAX_BYTES
] ??
'',
73 'maxchars' => $settings[self
::PARAM_MAX_CHARS
] ??
'',
76 if ( isset( $settings[self
::PARAM_MAX_CHARS
] )
77 && mb_strlen( $value, 'UTF-8' ) > $settings[self
::PARAM_MAX_CHARS
]
79 throw new ValidationException( $name, $value, $settings, 'maxchars', [
80 'maxbytes' => $settings[self
::PARAM_MAX_BYTES
] ??
'',
81 'maxchars' => $settings[self
::PARAM_MAX_CHARS
] ??
'',