MediaWiki REL1_35
JsonBodyValidator.php
Go to the documentation of this file.
1<?php
2
4
5use FormatJson;
10
15
20
24 public function __construct( array $bodyParamSettings ) {
25 $this->bodyParamSettings = $bodyParamSettings;
26 }
27
28 public function validateBody( RequestInterface $request ) {
29 $jsonStream = $request->getBody();
30 $status = FormatJson::parse( "$jsonStream", FormatJson::FORCE_ASSOC );
31
32 if ( !$status->isOK() ) {
33 throw new LocalizedHttpException(
34 new MessageValue( 'rest-json-body-parse-error', [ "$status" ] ),
35 400
36 );
37 }
38
39 $data = $status->value;
40
41 if ( !is_array( $data ) ) {
42 throw new LocalizedHttpException( new MessageValue( 'rest-bad-json-body' ), 400 );
43 }
44
45 foreach ( $this->bodyParamSettings as $name => $settings ) {
46 if ( !empty( $settings[ParamValidator::PARAM_REQUIRED] ) && !isset( $data[$name] ) ) {
47 throw new LocalizedHttpException(
48 new MessageValue( 'rest-missing-body-field', [ $name ] ), 400
49 );
50 }
51
52 if ( !isset( $data[$name] ) ) {
53 $data[$name] = $settings[ParamValidator::PARAM_DEFAULT] ?? null;
54 }
55
56 // TODO: use a ParamValidator to check field value, etc!
57 }
58
59 return $data;
60 }
61
62}
JSON formatter wrapper class.
validateBody(RequestInterface $request)
Validate the body of a request.
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.