MediaWiki REL1_37
ResponseFactory.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Rest;
4
5use HttpStatus;
6use InvalidArgumentException;
9use stdClass;
10use 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
24
28 public function __construct( $textFormatters ) {
29 $this->textFormatters = $textFormatters;
30 }
31
39 public function encodeJson( $value ) {
40 $json = json_encode( $value,
41 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE );
42 if ( $json === false ) {
43 throw new JsonEncodingException( json_last_error_msg(), json_last_error() );
44 }
45 return $json;
46 }
47
53 public function create() {
54 return new Response();
55 }
56
64 public function createJson( $value, $contentType = null ) {
65 $contentType = $contentType ?? self::CT_JSON;
66 $response = new Response( $this->encodeJson( $value ) );
67 $response->setHeader( 'Content-Type', $contentType );
68 return $response;
69 }
70
81 public function createNoContent() {
82 $response = new Response();
83 $response->setStatus( 204 );
84 return $response;
85 }
86
96 public function createPermanentRedirect( $target ) {
97 $response = $this->createRedirectBase( $target );
98 $response->setStatus( 301 );
99 return $response;
100 }
101
112 public function createLegacyTemporaryRedirect( $target ) {
113 $response = $this->createRedirectBase( $target );
114 $response->setStatus( 302 );
115 return $response;
116 }
117
126 public function createTemporaryRedirect( $target ) {
127 $response = $this->createRedirectBase( $target );
128 $response->setStatus( 307 );
129 return $response;
130 }
131
140 public function createSeeOther( $target ) {
141 $response = $this->createRedirectBase( $target );
142 $response->setStatus( 303 );
143 return $response;
144 }
145
156 public function createNotModified() {
157 $response = new Response();
158 $response->setStatus( 304 );
159 return $response;
160 }
161
169 public function createHttpError( $errorCode, array $bodyData = [] ) {
170 if ( $errorCode < 400 || $errorCode >= 600 ) {
171 throw new InvalidArgumentException( 'error code must be 4xx or 5xx' );
172 }
173 $response = $this->createJson( $bodyData + [
174 'httpCode' => $errorCode,
175 'httpReason' => HttpStatus::getMessage( $errorCode )
176 ] );
177 // TODO add link to error code documentation
178 $response->setStatus( $errorCode );
179 return $response;
180 }
181
192 $errorCode,
193 MessageValue $messageValue,
194 array $extraData = []
195 ) {
196 return $this->createHttpError(
197 $errorCode,
198 array_merge( $extraData, $this->formatMessage( $messageValue ) )
199 );
200 }
201
207 public function createFromException( Throwable $exception ) {
208 if ( $exception instanceof LocalizedHttpException ) {
209 $response = $this->createLocalizedHttpError(
210 $exception->getCode(),
211 $exception->getMessageValue(),
212 (array)$exception->getErrorData()
213 );
214 } elseif ( $exception instanceof ResponseException ) {
215 return $exception->getResponse();
216 } elseif ( $exception instanceof RedirectException ) {
217 $response = $this->createRedirectBase( $exception->getTarget() );
218 $response->setStatus( $exception->getCode() );
219 } elseif ( $exception instanceof HttpException ) {
220 if ( in_array( $exception->getCode(), [ 204, 304 ], true ) ) {
221 $response = $this->create();
222 $response->setStatus( $exception->getCode() );
223 } else {
224 $response = $this->createHttpError(
225 $exception->getCode(),
226 array_merge(
227 [ 'message' => $exception->getMessage() ],
228 (array)$exception->getErrorData()
229 )
230 );
231 }
232 } else {
233 $response = $this->createHttpError( 500, [
234 'message' => 'Error: exception of type ' . get_class( $exception ),
235 'exception' => MWExceptionHandler::getStructuredExceptionData( $exception )
236 ] );
237 // FIXME should we try to do something useful with ILocalizedException?
238 // FIXME should we try to do something useful with common MediaWiki errors like ReadOnlyError?
239 }
240 return $response;
241 }
242
250 public function createFromReturnValue( $value ) {
251 $originalValue = $value;
252 if ( is_scalar( $value ) ) {
253 $data = [ 'value' => $value ];
254 } elseif ( is_array( $value ) || $value instanceof stdClass ) {
255 $data = $value;
256 } else {
257 $type = gettype( $originalValue );
258 if ( $type === 'object' ) {
259 $type = get_class( $originalValue );
260 }
261 throw new InvalidArgumentException( __METHOD__ . ": Invalid return value type $type" );
262 }
263 $response = $this->createJson( $data );
264 return $response;
265 }
266
272 protected function createRedirectBase( $target ) {
273 $response = new Response( $this->getHyperLink( $target ) );
274 $response->setHeader( 'Content-Type', self::CT_HTML );
275 $response->setHeader( 'Location', $target );
276 return $response;
277 }
278
285 protected function getHyperLink( $url ) {
286 $url = htmlspecialchars( $url );
287 return "<!doctype html><title>Redirect</title><a href=\"$url\">$url</a>";
288 }
289
290 public function formatMessage( MessageValue $messageValue ) {
291 if ( !$this->textFormatters ) {
292 // For unit tests
293 return [];
294 }
295 $translations = [];
296 foreach ( $this->textFormatters as $formatter ) {
297 $lang = LanguageCode::bcp47( $formatter->getLangCode() );
298 $messageText = $formatter->format( $messageValue );
299 $translations[$lang] = $messageText;
300 }
301 return [ 'messageTranslations' => $translations ];
302 }
303
304}
Methods for dealing with language codes.
Handler class for MWExceptions.
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.
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