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.
24 class StringDef
extends TypeDef
{
27 * (integer) Maximum length of a string in bytes.
29 * ValidationException codes:
30 * - 'maxbytes': The string is too long. Data:
31 * - 'maxbytes': The maximum number of bytes allowed
32 * - 'maxchars': The maximum number of characters allowed
34 const PARAM_MAX_BYTES
= 'param-max-bytes';
37 * (integer) Maximum length of a string in characters (Unicode codepoints).
39 * The string is assumed to be encoded as UTF-8.
41 * ValidationException codes:
42 * - 'maxchars': The string is too long. Data:
43 * - 'maxbytes': The maximum number of bytes allowed
44 * - 'maxchars': The maximum number of characters allowed
46 const PARAM_MAX_CHARS
= 'param-max-chars';
48 protected $allowEmptyWhenRequired = false;
51 * @param Callbacks $callbacks
52 * @param array $options Options:
53 * - allowEmptyWhenRequired: (bool) Whether to reject the empty string when PARAM_REQUIRED.
56 public function __construct( Callbacks
$callbacks, array $options = [] ) {
57 parent
::__construct( $callbacks );
59 $this->allowEmptyWhenRequired
= !empty( $options['allowEmptyWhenRequired'] );
62 public function validate( $name, $value, array $settings, array $options ) {
63 if ( !$this->allowEmptyWhenRequired
&& $value === '' &&
64 !empty( $settings[ParamValidator
::PARAM_REQUIRED
] )
66 throw new ValidationException( $name, $value, $settings, 'missingparam', [] );
69 if ( isset( $settings[self
::PARAM_MAX_BYTES
] )
70 && strlen( $value ) > $settings[self
::PARAM_MAX_BYTES
]
72 throw new ValidationException( $name, $value, $settings, 'maxbytes', [
73 'maxbytes' => $settings[self
::PARAM_MAX_BYTES
] ??
'',
74 'maxchars' => $settings[self
::PARAM_MAX_CHARS
] ??
'',
77 if ( isset( $settings[self
::PARAM_MAX_CHARS
] )
78 && mb_strlen( $value, 'UTF-8' ) > $settings[self
::PARAM_MAX_CHARS
]
80 throw new ValidationException( $name, $value, $settings, 'maxchars', [
81 'maxbytes' => $settings[self
::PARAM_MAX_BYTES
] ??
'',
82 'maxchars' => $settings[self
::PARAM_MAX_CHARS
] ??
'',