MediaWiki  master
ResponseFactory.php
Go to the documentation of this file.
1 <?php
2 
3 namespace MediaWiki\Rest;
4 
5 use HttpStatus;
6 use InvalidArgumentException;
7 use LanguageCode;
9 use stdClass;
10 use Throwable;
13 
18  private const CT_PLAIN = 'text/plain; charset=utf-8';
19  private const CT_HTML = 'text/html; charset=utf-8';
20  private const CT_JSON = 'application/json';
21 
23  private $textFormatters;
24 
26  private $showExceptionDetails = false;
27 
31  public function __construct( $textFormatters ) {
32  $this->textFormatters = $textFormatters;
33  }
34 
42  public function setShowExceptionDetails( bool $showExceptionDetails ): void {
43  $this->showExceptionDetails = $showExceptionDetails;
44  }
45 
53  public function encodeJson( $value ) {
54  $json = json_encode( $value,
55  JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE );
56  if ( $json === false ) {
57  throw new JsonEncodingException( json_last_error_msg(), json_last_error() );
58  }
59  return $json;
60  }
61 
67  public function create() {
68  return new Response();
69  }
70 
78  public function createJson( $value, $contentType = null ) {
79  $contentType ??= self::CT_JSON;
80  $response = new Response( $this->encodeJson( $value ) );
81  $response->setHeader( 'Content-Type', $contentType );
82  return $response;
83  }
84 
95  public function createNoContent() {
96  $response = new Response();
97  $response->setStatus( 204 );
98  return $response;
99  }
100 
110  public function createPermanentRedirect( $target ) {
111  $response = $this->createRedirectBase( $target );
112  $response->setStatus( 301 );
113  return $response;
114  }
115 
126  public function createLegacyTemporaryRedirect( $target ) {
127  $response = $this->createRedirectBase( $target );
128  $response->setStatus( 302 );
129  return $response;
130  }
131 
140  public function createTemporaryRedirect( $target ) {
141  $response = $this->createRedirectBase( $target );
142  $response->setStatus( 307 );
143  return $response;
144  }
145 
154  public function createSeeOther( $target ) {
155  $response = $this->createRedirectBase( $target );
156  $response->setStatus( 303 );
157  return $response;
158  }
159 
170  public function createNotModified() {
171  $response = new Response();
172  $response->setStatus( 304 );
173  return $response;
174  }
175 
183  public function createHttpError( $errorCode, array $bodyData = [] ) {
184  if ( $errorCode < 400 || $errorCode >= 600 ) {
185  throw new InvalidArgumentException( 'error code must be 4xx or 5xx' );
186  }
187  $response = $this->createJson( $bodyData + [
188  'httpCode' => $errorCode,
189  'httpReason' => HttpStatus::getMessage( $errorCode )
190  ] );
191  // TODO add link to error code documentation
192  $response->setStatus( $errorCode );
193  return $response;
194  }
195 
205  public function createLocalizedHttpError(
206  $errorCode,
207  MessageValue $messageValue,
208  array $extraData = []
209  ) {
210  return $this->createHttpError(
211  $errorCode,
212  array_merge( $extraData, $this->formatMessage( $messageValue ) )
213  );
214  }
215 
221  public function createFromException( Throwable $exception ) {
222  if ( $exception instanceof LocalizedHttpException ) {
223  $response = $this->createLocalizedHttpError(
224  $exception->getCode(),
225  $exception->getMessageValue(),
226  (array)$exception->getErrorData()
227  );
228  } elseif ( $exception instanceof ResponseException ) {
229  return $exception->getResponse();
230  } elseif ( $exception instanceof RedirectException ) {
231  $response = $this->createRedirectBase( $exception->getTarget() );
232  $response->setStatus( $exception->getCode() );
233  } elseif ( $exception instanceof HttpException ) {
234  if ( in_array( $exception->getCode(), [ 204, 304 ], true ) ) {
235  $response = $this->create();
236  $response->setStatus( $exception->getCode() );
237  } else {
238  $response = $this->createHttpError(
239  $exception->getCode(),
240  array_merge(
241  [ 'message' => $exception->getMessage() ],
242  (array)$exception->getErrorData()
243  )
244  );
245  }
246  } elseif ( $this->showExceptionDetails ) {
247  $response = $this->createHttpError( 500, [
248  'message' => 'Error: exception of type ' . get_class( $exception ) . ': '
249  . $exception->getMessage(),
251  $exception,
252  MWExceptionHandler::CAUGHT_BY_OTHER
253  )
254  ] );
255  // XXX: should we try to do something useful with ILocalizedException?
256  // XXX: should we try to do something useful with common MediaWiki errors like ReadOnlyError?
257  } else {
258  $response = $this->createHttpError( 500, [
259  'message' => 'Error: exception of type ' . get_class( $exception ),
260  ] );
261  }
262  return $response;
263  }
264 
272  public function createFromReturnValue( $value ) {
273  $originalValue = $value;
274  if ( is_scalar( $value ) ) {
275  $data = [ 'value' => $value ];
276  } elseif ( is_array( $value ) || $value instanceof stdClass ) {
277  $data = $value;
278  } else {
279  $type = gettype( $originalValue );
280  if ( $type === 'object' ) {
281  $type = get_class( $originalValue );
282  }
283  throw new InvalidArgumentException( __METHOD__ . ": Invalid return value type $type" );
284  }
285  $response = $this->createJson( $data );
286  return $response;
287  }
288 
294  protected function createRedirectBase( $target ) {
295  $response = new Response( $this->getHyperLink( $target ) );
296  $response->setHeader( 'Content-Type', self::CT_HTML );
297  $response->setHeader( 'Location', $target );
298  return $response;
299  }
300 
307  protected function getHyperLink( $url ) {
308  $url = htmlspecialchars( $url, ENT_COMPAT );
309  return "<!doctype html><title>Redirect</title><a href=\"$url\">$url</a>";
310  }
311 
312  public function formatMessage( MessageValue $messageValue ) {
313  if ( !$this->textFormatters ) {
314  // For unit tests
315  return [];
316  }
317  $translations = [];
318  foreach ( $this->textFormatters as $formatter ) {
319  $lang = LanguageCode::bcp47( $formatter->getLangCode() );
320  $messageText = $formatter->format( $messageValue );
321  $translations[$lang] = $messageText;
322  }
323  return [ 'messageTranslations' => $translations ];
324  }
325 
326 }
static getMessage( $code)
Get the message associated with an HTTP response status code.
Definition: HttpStatus.php:34
Methods for dealing with language codes.
static bcp47( $code)
Get the normalised IANA language tag See unit test for examples.
Handler class for MWExceptions.
static getStructuredExceptionData(Throwable $e, $catcher=self::CAUGHT_BY_OTHER)
Get a structured representation of a Throwable.
This is the base exception class for non-fatal exceptions thrown from REST handlers.
This is an exception class that extends HttpException and will generate a redirect when handled.
This is an exception class that wraps a Response and extends HttpException.
Generates standardized response objects.
encodeJson( $value)
Encode a stdClass object or array to a JSON string.
create()
Create an unspecified response.
createFromException(Throwable $exception)
Turn a throwable into a JSON error response.
formatMessage(MessageValue $messageValue)
createJson( $value, $contentType=null)
Create a successful JSON response.
setShowExceptionDetails(bool $showExceptionDetails)
Control whether web responses may include a exception messager and backtrace.
createTemporaryRedirect( $target)
Creates a temporary (307) redirect.
createHttpError( $errorCode, array $bodyData=[])
Create a HTTP 4xx or 5xx response.
createPermanentRedirect( $target)
Creates a permanent (301) redirect.
createLegacyTemporaryRedirect( $target)
Creates a temporary (302) redirect.
createRedirectBase( $target)
Create a redirect response with type / response code unspecified.
createLocalizedHttpError( $errorCode, MessageValue $messageValue, array $extraData=[])
Create an HTTP 4xx or 5xx response with error message localisation.
createNoContent()
Create a 204 (No Content) response, used to indicate that an operation which does not return anything...
createFromReturnValue( $value)
Create a JSON response from an arbitrary value.
getHyperLink( $url)
Returns a minimal HTML document that links to the given URL, as suggested by RFC 7231 for 3xx respons...
createSeeOther( $target)
Creates a See Other (303) redirect.
createNotModified()
Create a 304 (Not Modified) response, used when the client has an up-to-date cached response.
Value object representing a message for i18n.
if(!isset( $args[0])) $lang