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 URL (can be relative)
84 public function createPermanentRedirect( $target ) {
85 $response = $this->createRedirectBase( $target );
86 $response->setStatus( 301 );
91 * Creates a temporary (307) redirect.
92 * This indicates that the operation the client was trying to perform can temporarily
93 * be achieved by using a different URL. Clients will preserve the request method when
94 * retrying the request with the new URL.
95 * @param string $target Redirect URL (can be relative)
98 public function createTemporaryRedirect( $target ) {
99 $response = $this->createRedirectBase( $target );
100 $response->setStatus( 307 );
105 * Creates a See Other (303) redirect.
106 * This indicates that the target resource might be of interest to the client, without
107 * necessarily implying that it is the same resource. The client will always use GET
108 * (or HEAD) when following the redirection. Useful for GET-after-POST.
109 * @param string $target Redirect URL (can be relative)
112 public function createSeeOther( $target ) {
113 $response = $this->createRedirectBase( $target );
114 $response->setStatus( 303 );
119 * Create a 304 (Not Modified) response, used when the client has an up-to-date cached response.
121 * Per RFC 7232 the response should contain all Cache-Control, Content-Location, Date,
122 * ETag, Expires, and Vary headers that would have been sent with the 200 OK answer
123 * if the requesting client did not have a valid cached response. This is the responsibility
124 * of the caller of this method.
128 public function createNotModified() {
129 $response = new Response();
130 $response->setStatus( 304 );
135 * Create a HTTP 4xx or 5xx response.
136 * @param int $errorCode HTTP error code
137 * @param array $bodyData An array of data to be included in the JSON response
139 * @throws InvalidArgumentException
141 public function createHttpError( $errorCode, array $bodyData = [] ) {
142 if ( $errorCode < 400 ||
$errorCode >= 600 ) {
143 throw new InvalidArgumentException( 'error code must be 4xx or 5xx' );
145 $response = $this->createJson( $bodyData +
[
146 'httpCode' => $errorCode,
147 'httpReason' => HttpStatus
::getMessage( $errorCode )
149 // TODO add link to error code documentation
150 $response->setStatus( $errorCode );
155 * Turn an exception into a JSON error response.
156 * @param Exception|Throwable $exception
159 public function createFromException( $exception ) {
160 if ( $exception instanceof HttpException
) {
161 // FIXME can HttpException represent 2xx or 3xx responses?
162 $response = $this->createHttpError( $exception->getCode(),
163 [ 'message' => $exception->getMessage() ] );
165 $response = $this->createHttpError( 500, [
166 'message' => 'Error: exception of type ' . get_class( $exception ),
167 'exception' => MWExceptionHandler
::getStructuredExceptionData( $exception )
169 // FIXME should we try to do something useful with ILocalizedException?
170 // FIXME should we try to do something useful with common MediaWiki errors like ReadOnlyError?
176 * Create a JSON response from an arbitrary value.
177 * This is a fallback; it's preferable to use createJson() instead.
178 * @param mixed $value A structure containing only scalars, arrays and stdClass objects
180 * @throws InvalidArgumentException When $value cannot be reasonably represented as JSON
182 public function createFromReturnValue( $value ) {
183 $originalValue = $value;
184 if ( is_scalar( $value ) ) {
185 $data = [ 'value' => $value ];
186 } elseif ( is_array( $value ) ||
$value instanceof stdClass
) {
189 $type = gettype( $originalValue );
190 if ( $type === 'object' ) {
191 $type = get_class( $originalValue );
193 throw new InvalidArgumentException( __METHOD__
. ": Invalid return value type $type" );
195 $response = $this->createJson( $data );
200 * Create a redirect response with type / response code unspecified.
201 * @param string $target Redirect target (an absolute URL)
204 protected function createRedirectBase( $target ) {
205 $response = new Response( $this->getHyperLink( $target ) );
206 $response->setHeader( 'Content-Type', self
::CT_HTML
);
207 $response->setHeader( 'Location', $target );
212 * Returns a minimal HTML document that links to the given URL, as suggested by
213 * RFC 7231 for 3xx responses.
214 * @param string $url An absolute URL
217 protected function getHyperLink( $url ) {
218 $url = htmlspecialchars( $url );
219 return "<!doctype html><title>Redirect</title><a href=\"$url\">$url</a>";