3 namespace MediaWiki\Rest
;
9 class ResponseFactory
{
10 const CT_PLAIN
= 'text/plain; charset=utf-8';
11 const CT_JSON
= 'application/json';
13 public function create404() {
14 $response = new Response( 'Path not found' );
15 $response->setStatus( 404 );
16 $response->setHeader( 'Content-Type', self
::CT_PLAIN
);
20 public function create500( $message ) {
21 $response = new Response( $message );
22 $response->setStatus( 500 );
23 $response->setHeader( 'Content-Type', self
::CT_PLAIN
);
27 public function createFromException( \Exception
$exception ) {
28 if ( $exception instanceof HttpException
) {
29 $response = new Response( $exception->getMessage() );
30 $response->setStatus( $exception->getCode() );
31 $response->setHeader( 'Content-Type', self
::CT_PLAIN
);
34 return $this->create500( "Error: exception of type " . gettype( $exception ) );
38 public function createFromReturnValue( $value ) {
39 if ( is_scalar( $value )
40 ||
( is_object( $value ) && method_exists( $value, '__toString' ) )
42 $value = [ 'value' => (string)$value ];
44 $json = json_encode( $value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
);
45 if ( $json === false ) {
46 throw new JsonEncodingException( json_last_error_msg(), json_last_error() );
48 $response = new Response( $json );
49 $response->setHeader( 'Content-Type', self
::CT_JSON
);