MediaWiki  master
JsonBodyValidator.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use FormatJson;
10 
14 class JsonBodyValidator implements BodyValidator {
15 
19  private $bodyParamSettings;
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.
Definition: FormatJson.php:26
static parse( $value, $options=0)
Decodes a JSON string.
Definition: FormatJson.php:160
const FORCE_ASSOC
If set, treat JSON objects '{...}' as associative arrays.
Definition: FormatJson.php:63
validateBody(RequestInterface $request)
Validate the body of a request.
Value object representing a message for i18n.
Service for formatting and validating API parameters.
const PARAM_DEFAULT
(mixed) Default value of the parameter.
const PARAM_REQUIRED
(bool) Indicate that the parameter is required.
A request interface similar to PSR-7's ServerRequestInterface.
getBody()
Gets the body of the message.
Interface for validating a request body.