3 namespace MediaWiki\Rest
;
7 use InvalidArgumentException
;
8 use MWExceptionHandler
;
13 * Generates standardized response objects.
15 class ResponseFactory
{
17 const CT_PLAIN
= 'text/plain; charset=utf-8';
18 const CT_HTML
= 'text/html; charset=utf-8';
19 const CT_JSON
= 'application/json';
22 * Encode a stdClass object or array to a JSON string
24 * @param array|stdClass $value
26 * @throws JsonEncodingException
28 public function encodeJson( $value ) {
29 $json = json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
30 if ( $json === false ) {
31 throw new JsonEncodingException( json_last_error_msg(), json_last_error() );
37 * Create an unspecified response. It is the caller's responsibility to set specifics
38 * like response code, content type etc.
41 public function create() {
42 return new Response();
46 * Create a successful JSON response.
47 * @param array|stdClass $value JSON value
48 * @param string|null $contentType HTTP content type (should be 'application/json+...')
49 * or null for plain 'application/json'
52 public function createJson( $value, $contentType = null ) {
53 $contentType = $contentType ?? self
::CT_JSON
;
54 $response = new Response( $this->encodeJson( $value ) );
55 $response->setHeader( 'Content-Type', $contentType );
60 * Create a 204 (No Content) response, used to indicate that an operation which does
61 * not return anything (e.g. a PUT request) was successful.
63 * Headers are generally interpreted to refer to the target of the operation. E.g. if
64 * this was a PUT request, the caller of this method might want to add an ETag header
65 * describing the created resource.
69 public function createNoContent() {
70 $response = new Response();
71 $response->setStatus( 204 );
76 * Creates a permanent (301) redirect.
77 * This indicates that the caller of the API should update their indexes and call
78 * the new URL in the future. 301 redirects tend to get cached and are hard to undo.
79 * Client behavior for methods other than GET/HEAD is not well-defined and this type
80 * of response should be avoided in such cases.
81 * @param string $target Redirect target (an absolute URL)
84 public function createPermanentRedirect( $target ) {
85 $response = $this->createRedirectBase( $target );
86 $response->setStatus( 301 );
91 * Creates a temporary (302) redirect.
92 * HTTP 302 was underspecified and has been superseded by 303 (when the redirected request
93 * should be a GET, regardless of what the current request is) and 307 (when the method should
94 * not be changed), but might still be needed for HTTP 1.0 clients or to match legacy behavior.
95 * @param string $target Redirect target (an absolute URL)
97 * @see self::createTemporaryRedirect()
98 * @see self::createSeeOther()
100 public function createLegacyTemporaryRedirect( $target ) {
101 $response = $this->createRedirectBase( $target );
102 $response->setStatus( 302 );
107 * Creates a temporary (307) redirect.
108 * This indicates that the operation the client was trying to perform can temporarily
109 * be achieved by using a different URL. Clients will preserve the request method when
110 * retrying the request with the new URL.
111 * @param string $target Redirect target (an absolute URL)
114 public function createTemporaryRedirect( $target ) {
115 $response = $this->createRedirectBase( $target );
116 $response->setStatus( 307 );
121 * Creates a See Other (303) redirect.
122 * This indicates that the target resource might be of interest to the client, without
123 * necessarily implying that it is the same resource. The client will always use GET
124 * (or HEAD) when following the redirection. Useful for GET-after-POST.
125 * @param string $target Redirect target (an absolute URL)
128 public function createSeeOther( $target ) {
129 $response = $this->createRedirectBase( $target );
130 $response->setStatus( 303 );
135 * Create a 304 (Not Modified) response, used when the client has an up-to-date cached response.
137 * Per RFC 7232 the response should contain all Cache-Control, Content-Location, Date,
138 * ETag, Expires, and Vary headers that would have been sent with the 200 OK answer
139 * if the requesting client did not have a valid cached response. This is the responsibility
140 * of the caller of this method.
144 public function createNotModified() {
145 $response = new Response();
146 $response->setStatus( 304 );
151 * Create a HTTP 4xx or 5xx response.
152 * @param int $errorCode HTTP error code
153 * @param array $bodyData An array of data to be included in the JSON response
155 * @throws InvalidArgumentException
157 public function createHttpError( $errorCode, array $bodyData = [] ) {
158 if ( $errorCode < 400 ||
$errorCode >= 600 ) {
159 throw new InvalidArgumentException( 'error code must be 4xx or 5xx' );
161 $response = $this->createJson( $bodyData +
[
162 'httpCode' => $errorCode,
163 'httpReason' => HttpStatus
::getMessage( $errorCode )
165 // TODO add link to error code documentation
166 $response->setStatus( $errorCode );
171 * Turn an exception into a JSON error response.
172 * @param Exception|Throwable $exception
175 public function createFromException( $exception ) {
176 if ( $exception instanceof HttpException
) {
177 // FIXME can HttpException represent 2xx or 3xx responses?
178 $response = $this->createHttpError( $exception->getCode(),
179 [ 'message' => $exception->getMessage() ] );
181 $response = $this->createHttpError( 500, [
182 'message' => 'Error: exception of type ' . get_class( $exception ),
183 'exception' => MWExceptionHandler
::getStructuredExceptionData( $exception )
185 // FIXME should we try to do something useful with ILocalizedException?
186 // FIXME should we try to do something useful with common MediaWiki errors like ReadOnlyError?
192 * Create a JSON response from an arbitrary value.
193 * This is a fallback; it's preferable to use createJson() instead.
194 * @param mixed $value A structure containing only scalars, arrays and stdClass objects
196 * @throws InvalidArgumentException When $value cannot be reasonably represented as JSON
198 public function createFromReturnValue( $value ) {
199 $originalValue = $value;
200 if ( is_scalar( $value ) ) {
201 $data = [ 'value' => $value ];
202 } elseif ( is_array( $value ) ||
$value instanceof stdClass
) {
205 $type = gettype( $originalValue );
206 if ( $type === 'object' ) {
207 $type = get_class( $originalValue );
209 throw new InvalidArgumentException( __METHOD__
. ": Invalid return value type $type" );
211 $response = $this->createJson( $data );
216 * Create a redirect response with type / response code unspecified.
217 * @param string $target Redirect target (an absolute URL)
220 protected function createRedirectBase( $target ) {
221 $response = new Response( $this->getHyperLink( $target ) );
222 $response->setHeader( 'Content-Type', self
::CT_HTML
);
223 $response->setHeader( 'Location', $target );
228 * Returns a minimal HTML document that links to the given URL, as suggested by
229 * RFC 7231 for 3xx responses.
230 * @param string $url An absolute URL
233 protected function getHyperLink( $url ) {
234 $url = htmlspecialchars( $url );
235 return "<!doctype html><title>Redirect</title><a href=\"$url\">$url</a>";