MediaWiki  master
Validator.php
Go to the documentation of this file.
1 <?php
2 
4 
12 use Wikimedia\ObjectFactory;
24 
32 class Validator {
33 
35  private const TYPE_DEFS = [
36  'boolean' => [ 'class' => BooleanDef::class ],
37  'enum' => [ 'class' => EnumDef::class ],
38  'integer' => [ 'class' => IntegerDef::class ],
39  'float' => [ 'class' => FloatDef::class ],
40  'double' => [ 'class' => FloatDef::class ],
41  'NULL' => [
42  'class' => StringDef::class,
43  'args' => [ [
44  'allowEmptyWhenRequired' => true,
45  ] ],
46  ],
47  'password' => [ 'class' => PasswordDef::class ],
48  'string' => [ 'class' => StringDef::class ],
49  'timestamp' => [ 'class' => TimestampDef::class ],
50  'upload' => [ 'class' => UploadDef::class ],
51  'expiry' => [ 'class' => ExpiryDef::class ],
52  'user' => [
53  'class' => UserDef::class,
54  'services' => [ 'UserFactory', 'TitleFactory', 'UserNameUtils' ]
55  ],
56  ];
57 
59  private const NO_BODY_METHODS = [ 'GET', 'HEAD', 'DELETE' ];
60 
62  private const BODY_METHODS = [ 'POST', 'PUT' ];
63 
65  private const FORM_DATA_CONTENT_TYPES = [
66  'application/x-www-form-urlencoded',
67  'multipart/form-data',
68  ];
69 
71  private $paramValidator;
72 
80  public function __construct(
81  ObjectFactory $objectFactory,
82  PermissionManager $permissionManager,
83  RequestInterface $request,
84  UserIdentity $user
85  ) {
86  $this->paramValidator = new ParamValidator(
87  new ParamValidatorCallbacks( $permissionManager, $request, $user ),
88  $objectFactory,
89  [
90  'typeDefs' => self::TYPE_DEFS,
91  ]
92  );
93  }
94 
101  public function validateParams( array $paramSettings ) {
102  $validatedParams = [];
103  foreach ( $paramSettings as $name => $settings ) {
104  try {
105  $validatedParams[$name] = $this->paramValidator->getValue( $name, $settings, [
106  'source' => $settings[Handler::PARAM_SOURCE] ?? 'unspecified',
107  ] );
108  } catch ( ValidationException $e ) {
109  throw new LocalizedHttpException( $e->getFailureMessage(), 400, [
110  'error' => 'parameter-validation-failed',
111  'name' => $e->getParamName(),
112  'value' => $e->getParamValue(),
113  'failureCode' => $e->getFailureMessage()->getCode(),
114  'failureData' => $e->getFailureMessage()->getData(),
115  ] );
116  }
117  }
118  return $validatedParams;
119  }
120 
133  public function validateBody( RequestInterface $request, Handler $handler ) {
134  $method = strtoupper( trim( $request->getMethod() ) );
135 
136  // If the method should never have a body, don't bother validating.
137  if ( in_array( $method, self::NO_BODY_METHODS, true ) ) {
138  return null;
139  }
140 
141  // Get the content type
142  list( $ct ) = explode( ';', $request->getHeaderLine( 'Content-Type' ), 2 );
143  $ct = strtolower( trim( $ct ) );
144  if ( $ct === '' ) {
145  // No Content-Type was supplied. RFC 7231 ยง 3.1.1.5 allows this, but since it's probably a
146  // client error let's return a 415. But don't 415 for unknown methods and an empty body.
147  if ( !in_array( $method, self::BODY_METHODS, true ) ) {
148  $body = $request->getBody();
149  $size = $body->getSize();
150  if ( $size === null ) {
151  // No size available. Try reading 1 byte.
152  if ( $body->isSeekable() ) {
153  $body->rewind();
154  }
155  $size = $body->read( 1 ) === '' ? 0 : 1;
156  }
157  if ( $size === 0 ) {
158  return null;
159  }
160  }
161  throw new HttpException( "A Content-Type header must be supplied with a request payload.", 415, [
162  'error' => 'no-content-type',
163  ] );
164  }
165 
166  // Form data is parsed into $_POST and $_FILES by PHP and from there is accessed as parameters,
167  // don't bother trying to handle these via BodyValidator too.
168  if ( in_array( $ct, self::FORM_DATA_CONTENT_TYPES, true ) ) {
169  return null;
170  }
171 
172  // Validate the body. BodyValidator throws an HttpException on failure.
173  return $handler->getBodyValidator( $ct )->validateBody( $request );
174  }
175 
176 }
MediaWiki\Rest\Handler
Definition: AbstractContributionHandler.php:3
MediaWiki\Rest\Validator\Validator\__construct
__construct(ObjectFactory $objectFactory, PermissionManager $permissionManager, RequestInterface $request, UserIdentity $user)
Definition: Validator.php:80
Wikimedia\ParamValidator\ValidationException
Error reporting for ParamValidator.
Definition: ValidationException.php:16
MediaWiki\Rest\Validator\Validator
Wrapper for ParamValidator.
Definition: Validator.php:32
MediaWiki\Rest\Handler\PARAM_SOURCE
const PARAM_SOURCE
(string) ParamValidator constant to specify the source of the parameter.
Definition: Handler.php:22
Wikimedia\ParamValidator\TypeDef\EnumDef
Type definition for enumeration types.
Definition: EnumDef.php:32
Wikimedia\ParamValidator\ValidationException\getParamName
getParamName()
Fetch the parameter name that failed validation.
Definition: ValidationException.php:71
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
MediaWiki\Rest\Handler
Base class for REST route handlers.
Definition: Handler.php:16
Wikimedia\ParamValidator\ParamValidator::TypeDef\UserDef
Type definition for user types.
Definition: UserDef.php:25
MediaWiki\Rest\Validator\ParamValidatorCallbacks
Definition: ParamValidatorCallbacks.php:13
MediaWiki\Rest\RequestInterface\getBody
getBody()
Gets the body of the message.
Wikimedia\ParamValidator\ValidationException\getParamValue
getParamValue()
Fetch the parameter value that failed validation.
Definition: ValidationException.php:79
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:16
Wikimedia\ParamValidator\ValidationException\getFailureMessage
getFailureMessage()
Fetch the validation failure message.
Definition: ValidationException.php:63
MediaWiki\Rest\Validator\Validator\validateParams
validateParams(array $paramSettings)
Validate parameters.
Definition: Validator.php:101
MediaWiki\Rest\RequestInterface\getMethod
getMethod()
Retrieves the HTTP method of the request.
Wikimedia\ParamValidator\TypeDef\FloatDef
Type definition for a floating-point type.
Definition: FloatDef.php:29
Wikimedia\ParamValidator\TypeDef\StringDef
Type definition for string types.
Definition: StringDef.php:24
Wikimedia\ParamValidator\TypeDef\BooleanDef
Type definition for boolean types.
Definition: BooleanDef.php:23
MediaWiki\Permissions\PermissionManager
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Definition: PermissionManager.php:49
Wikimedia\ParamValidator\TypeDef\TimestampDef
Type definition for timestamp types.
Definition: TimestampDef.php:32
MediaWiki\Rest\RequestInterface
A request interface similar to PSR-7's ServerRequestInterface.
Definition: RequestInterface.php:39
MediaWiki\Rest\HttpException
This is the base exception class for non-fatal exceptions thrown from REST handlers.
Definition: HttpException.php:12
Wikimedia\ParamValidator\TypeDef\PasswordDef
Type definition for "password" types.
Definition: PasswordDef.php:16
MediaWiki\Rest\Validator\Validator\validateBody
validateBody(RequestInterface $request, Handler $handler)
Validate the body of a request.
Definition: Validator.php:133
Wikimedia\ParamValidator\TypeDef\IntegerDef
Type definition for integer types.
Definition: IntegerDef.php:23
Wikimedia\ParamValidator\TypeDef\UploadDef
Type definition for upload types.
Definition: UploadDef.php:34
MediaWiki\Rest\Validator
Definition: BodyValidator.php:3
MediaWiki\Rest\RequestInterface\getHeaderLine
getHeaderLine( $name)
Retrieves a comma-separated string of the values for a single header.
MediaWiki\Rest\Validator\Validator\$paramValidator
ParamValidator $paramValidator
Definition: Validator.php:64
Wikimedia\ParamValidator\ParamValidator
Service for formatting and validating API parameters.
Definition: ParamValidator.php:42
MediaWiki\Rest\Handler\getBodyValidator
getBodyValidator( $contentType)
Fetch the BodyValidator.
Definition: Handler.php:246
MediaWiki\Rest\LocalizedHttpException
@newable
Definition: LocalizedHttpException.php:10