ParamValidator: Flag as unstable for 1.34
[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 * @unstable
23 */
24 class StringDef extends TypeDef {
25
26 /**
27 * (integer) Maximum length of a string in bytes.
28 *
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
33 */
34 const PARAM_MAX_BYTES = 'param-max-bytes';
35
36 /**
37 * (integer) Maximum length of a string in characters (Unicode codepoints).
38 *
39 * The string is assumed to be encoded as UTF-8.
40 *
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
45 */
46 const PARAM_MAX_CHARS = 'param-max-chars';
47
48 protected $allowEmptyWhenRequired = false;
49
50 /**
51 * @param Callbacks $callbacks
52 * @param array $options Options:
53 * - allowEmptyWhenRequired: (bool) Whether to reject the empty string when PARAM_REQUIRED.
54 * Defaults to false.
55 */
56 public function __construct( Callbacks $callbacks, array $options = [] ) {
57 parent::__construct( $callbacks );
58
59 $this->allowEmptyWhenRequired = !empty( $options['allowEmptyWhenRequired'] );
60 }
61
62 public function validate( $name, $value, array $settings, array $options ) {
63 if ( !$this->allowEmptyWhenRequired && $value === '' &&
64 !empty( $settings[ParamValidator::PARAM_REQUIRED] )
65 ) {
66 throw new ValidationException( $name, $value, $settings, 'missingparam', [] );
67 }
68
69 if ( isset( $settings[self::PARAM_MAX_BYTES] )
70 && strlen( $value ) > $settings[self::PARAM_MAX_BYTES]
71 ) {
72 throw new ValidationException( $name, $value, $settings, 'maxbytes', [
73 'maxbytes' => $settings[self::PARAM_MAX_BYTES] ?? '',
74 'maxchars' => $settings[self::PARAM_MAX_CHARS] ?? '',
75 ] );
76 }
77 if ( isset( $settings[self::PARAM_MAX_CHARS] )
78 && mb_strlen( $value, 'UTF-8' ) > $settings[self::PARAM_MAX_CHARS]
79 ) {
80 throw new ValidationException( $name, $value, $settings, 'maxchars', [
81 'maxbytes' => $settings[self::PARAM_MAX_BYTES] ?? '',
82 'maxchars' => $settings[self::PARAM_MAX_CHARS] ?? '',
83 ] );
84 }
85
86 return $value;
87 }
88
89 }