Merge "Follow up to 'Remove support for the deprecated Key header'"
[lhc/web/wiklou.git] / includes / libs / ParamValidator / TypeDef / StringDef.php
1 <?php
2
3 namespace Wikimedia\ParamValidator\TypeDef;
4
5 use Wikimedia\ParamValidator\Callbacks;
6 use Wikimedia\ParamValidator\ParamValidator;
7 use Wikimedia\ParamValidator\TypeDef;
8 use Wikimedia\ParamValidator\ValidationException;
9
10 /**
11 * Type definition for string types
12 *
13 * The result from validate() is a PHP string.
14 *
15 * ValidationException codes:
16 * - 'missingparam': The parameter is the empty string (and that's not allowed). No data.
17 *
18 * Additional codes may be generated when using certain PARAM constants. See
19 * the constants' documentation for details.
20 *
21 * @since 1.34
22 */
23 class StringDef extends TypeDef {
24
25 /**
26 * (integer) Maximum length of a string in bytes.
27 *
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
32 */
33 const PARAM_MAX_BYTES = 'param-max-bytes';
34
35 /**
36 * (integer) Maximum length of a string in characters (Unicode codepoints).
37 *
38 * The string is assumed to be encoded as UTF-8.
39 *
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
44 */
45 const PARAM_MAX_CHARS = 'param-max-chars';
46
47 protected $allowEmptyWhenRequired = false;
48
49 /**
50 * @param Callbacks $callbacks
51 * @param array $options Options:
52 * - allowEmptyWhenRequired: (bool) Whether to reject the empty string when PARAM_REQUIRED.
53 * Defaults to false.
54 */
55 public function __construct( Callbacks $callbacks, array $options = [] ) {
56 parent::__construct( $callbacks );
57
58 $this->allowEmptyWhenRequired = !empty( $options['allowEmptyWhenRequired'] );
59 }
60
61 public function validate( $name, $value, array $settings, array $options ) {
62 if ( !$this->allowEmptyWhenRequired && $value === '' &&
63 !empty( $settings[ParamValidator::PARAM_REQUIRED] )
64 ) {
65 throw new ValidationException( $name, $value, $settings, 'missingparam', [] );
66 }
67
68 if ( isset( $settings[self::PARAM_MAX_BYTES] )
69 && strlen( $value ) > $settings[self::PARAM_MAX_BYTES]
70 ) {
71 throw new ValidationException( $name, $value, $settings, 'maxbytes', [
72 'maxbytes' => $settings[self::PARAM_MAX_BYTES] ?? '',
73 'maxchars' => $settings[self::PARAM_MAX_CHARS] ?? '',
74 ] );
75 }
76 if ( isset( $settings[self::PARAM_MAX_CHARS] )
77 && mb_strlen( $value, 'UTF-8' ) > $settings[self::PARAM_MAX_CHARS]
78 ) {
79 throw new ValidationException( $name, $value, $settings, 'maxchars', [
80 'maxbytes' => $settings[self::PARAM_MAX_BYTES] ?? '',
81 'maxchars' => $settings[self::PARAM_MAX_CHARS] ?? '',
82 ] );
83 }
84
85 return $value;
86 }
87
88 }