MediaWiki 1.41.2
JsonBodyValidator.php
Go to the documentation of this file.
1<?php
2
4
5use FormatJson;
12
17
21 private $bodyParamSettings;
22
26 public function __construct( array $bodyParamSettings ) {
27 $this->bodyParamSettings = $bodyParamSettings;
28 }
29
30 public function validateBody( RequestInterface $request ) {
31 $jsonStream = $request->getBody();
32 $status = FormatJson::parse( "$jsonStream", FormatJson::FORCE_ASSOC );
33
34 if ( !$status->isOK() ) {
35 throw new LocalizedHttpException(
36 new MessageValue( 'rest-json-body-parse-error', [ "$status" ] ),
37 400
38 );
39 }
40
41 $data = $status->value;
42
43 if ( !is_array( $data ) ) {
44 throw new LocalizedHttpException( new MessageValue( 'rest-bad-json-body' ), 400 );
45 }
46
47 $uncheckedBodyKeys = array_fill_keys( array_keys( $data ), true );
48 foreach ( $this->bodyParamSettings as $name => $settings ) {
49 if ( !empty( $settings[ParamValidator::PARAM_REQUIRED] ) && !isset( $data[$name] ) ) {
50 throw new LocalizedHttpException(
51 new MessageValue( 'rest-missing-body-field', [ $name ] ), 400
52 );
53 }
54
55 if ( !isset( $data[$name] ) ) {
56 $data[$name] = $settings[ParamValidator::PARAM_DEFAULT] ?? null;
57 }
58
59 unset( $uncheckedBodyKeys[$name] );
60 // TODO: use a ParamValidator to check field value, etc!
61 }
62 if ( $uncheckedBodyKeys ) {
63 throw new LocalizedHttpException(
64 new MessageValue(
65 'rest-extraneous-body-fields',
66 [ new ListParam( ListType::COMMA, array_keys( $uncheckedBodyKeys ) ) ]
67 ),
68 400
69 );
70 }
71
72 return $data;
73 }
74
75}
JSON formatter wrapper class.
validateBody(RequestInterface $request)
Validate the body of a request.
Value object representing a message parameter that consists of a list of values.
Definition ListParam.php:12
The constants used to specify list types.
Definition ListType.php:9
Value object representing a message for i18n.
Service for formatting and validating API parameters.
A request interface similar to PSR-7's ServerRequestInterface.
getBody()
Gets the body of the message.
Interface for validating a request body.