Get response for MethodNotAllowed exception.

@param MethodNotAllowed $exception
@return ResponseInterface
163358
protected function getMethodNotAllowedResponse(MethodNotAllowed $exception): ResponseInterface
    {
        return (new Response())
            ->withStatusCode(405)
            ->withHeader('Allow', implode(', ', $exception->getAllowedMethods()))
            ->withBody([
                'type' => '',
                'title' => 'Method not allowed.',
                'method' => $exception->getMethod(),
                'allowed_methods' => $exception->getAllowedMethods(),
            ]);
    }
855300
private function parseExceptionForErrorMessages(Exception $exception)
    {
        if (! $exception instanceof BadResponseException) {
            return new ApiException($exception->getMessage(), 0, $exception);
        }

        $response = $exception->getResponse();

        if (null === $response) {
            return new ApiException('Response is NULL.', 0, $exception);
        }

        Psr7\rewind_body($response);
        $responseBody = $response->getBody()->getContents();
        $decodedResponseBody = json_decode($responseBody, true);

        if (null !== $decodedResponseBody && isset($decodedResponseBody['error']['message']['value'])) {
            $errorMessage = $decodedResponseBody['error']['message']['value'];
        } else {
            $errorMessage = $responseBody;
        }

        $this->checkWhetherRateLimitHasBeenReached($response, $errorMessage);

        return new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $exception);
    }
571926
public function fulfillRequest()
    {
        if (! $this->supportsMethod($this->request->method)) {
            throw new Exception(
                'Method not allowed',
                static::ERROR_SCOPE | static::ERROR_HTTP_METHOD_NOT_ALLOWED,
                BaseResponse::HTTP_METHOD_NOT_ALLOWED
            );
        }

        $methodName = static::methodHandlerName($this->request->method);
        $models = $this->{$methodName}($this->request);

        if (is_null($models)) {
            throw new Exception(
                'Unknown ID',
                static::ERROR_SCOPE | static::ERROR_UNKNOWN_ID,
                BaseResponse::HTTP_NOT_FOUND
            );
        }

        if ($models instanceof Response) {
            $response = $models;
        } elseif ($models instanceof LengthAwarePaginator) {
            $items = new Collection($models->items());
            foreach ($items as $model) {
                $this->loadRelatedModels($model);
            }

            $response = new Response($items, static::successfulHttpStatusCode($this->request->method));

            $response->links = $this->getPaginationLinks($models);
            $response->included = $this->getIncludedModels($items);
            $response->errors = $this->getNonBreakingErrors();
        } else {
            if ($models instanceof Collection) {
                foreach ($models as $model) {
                    $this->loadRelatedModels($model);
                }
            } else {
                $this->loadRelatedModels($models);
            }

            $response = new Response($models, static::successfulHttpStatusCode($this->request->method, $models));

            $response->included = $this->getIncludedModels($models);
            $response->errors = $this->getNonBreakingErrors();
        }

        return $response;
    }
276005
public function options()
    {
        if (!($this->response instanceof ResponseInterface)) {
            throw new MethodNotAllowed();
        }

        // Get all implemented methods for this resources
        $methods = get_class_methods(get_class($this));

        // Get supported verbs
        $validMethods = $this->container['validHttpVerbs'];

        // Loop though class functions/methods
        foreach ($methods as $key => &$method) {
            $method = strtoupper($method);
            // If class function/method isn't a verb, then unset it
            if (!in_array($method, $validMethods)) {
                unset($methods[$key]);
            }
        }

        // Set accept header
        $this->response = $this->response->withAddedHeader('Allow', implode(', ', $methods));

        // Prepare output
        $output = [];
        $output['Content-Type'] = $this->container['contentTypes'];
        $output['Accept'] = $this->container['acceptTypes'];

        foreach ($methods as $verb) {
            $doc = $this->parseMethodDoc($verb);

            // Check if there is any output to show
            if (!empty($doc)) {
                $output['methods'][$verb] = $doc;
            }
        }

        // return output
        return $output;
    }
1149650
public function getResponse( RequestInterface $request, PhpException $exception ) {
		$response = $this->toResponse( $exception );

		if ( $response !== false ) {
			return $response;
		}

		if ( ! $this->debug ) {
			return Response::error( 500 );
		}

		return $this->toDebugResponse( $request, $exception );
	}
369368
private function handleError(ServerRequestInterface $request, HttpErrorException $exception): ResponseInterface
    {
        $request = $request->withAttribute($this->attribute, $exception);
        $handler = $this->handler ?: new ErrorHandlerDefault();

        return $handler->handle($request);
    }
1225129
protected function createRedirectErrorResponse(OAuthRedirectException $exception): ResponseInterface
    {
        $parameters = $this->filterNulls([
            'error'             => $exception->getErrorCode(),
            'error_description' => $exception->getErrorDescription(),
            'error_uri'         => $exception->getErrorUri(),
            'state'             => $exception->getState(),
        ]);

        $this->logDebug('Sending OAuth error via redirect.', $parameters);

        $fragment = $this->encodeAsXWwwFormUrlencoded($parameters);
        $uri      = (new Uri($exception->getRedirectUri()))->withFragment($fragment);

        $response = new RedirectResponse($uri, 302, $exception->getHttpHeaders());

        return $response;
    }
1234981
private function makeMethodNotAllowedResponse(array $methods, Request $request): Promise {
        return call(function () use ($methods, $request) {
            /** @var \Amp\Http\Server\Response $response */
            $response = yield $this->errorHandler->handleError(Status::METHOD_NOT_ALLOWED, null, $request);
            $response->setHeader("allow", \implode(", ", $methods));
            return $response;
        });
    }
282018
public function add()
    {
        if (!$this->request->is(['get', 'post'])) {
            throw new MethodNotAllowedException();
        }

        /** @var User $user */
        $user = $this->Users->newEntity(null, ['associated' => 'Groups']);

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->data, ['associated' => 'Groups']);
            $user->set('password', Text::uuid());

            if ($this->Users->save($user, ['associated' => 'Groups'])) {
                $this->Users->Tokens->invalidateExistingTokens($user->id, TokensTable::TYPE_EMAIL_VERIFICATION);
                $token = $this->Users->Tokens->generateToken($user, TokensTable::TYPE_EMAIL_VERIFICATION);
                $this->getMailer('Wasabi/Core.User')->send('verifyAndResetPasswordEmail', [$user, $token]);
                $this->Flash->success(__d('pb', 'The user <strong>{0}</strong> has been created.', $user->fullName()));
                $this->redirect(['action' => 'index']);
                return;
            } else {
                $this->Flash->error($this->formErrorMessage);
            }
        }

        $groups = $this->Users->Groups->find('list')->order('id ASC');

        // users that are no admin, may not select the super admin group
        if (Wasabi::user()->hasAccessLevel(Permission::OWN)) {
            $groups->where(['id <>' => 1]);
        }

        $this->set([
            'user' => $user,
            'groups' => $groups,
            'languages' => Hash::map(Configure::read('languages.backend'), '{n}', function ($language) {
                return [
                    'value' => $language->id,
                    'text' => $language->name
                ];
            })
        ]);
    }
506578
protected function errorResponse(\Exception $exception)
    {
        $error = $this->config->get('datatables.error');
        $debug = $this->config->get('app.debug');

        if ($error === 'throw' || (! $error && ! $debug)) {
            throw new Exception($exception->getMessage(), $code = 0, $exception);
        }

        $this->getLogger()->error($exception);

        return new JsonResponse([
            'draw'            => (int) $this->request->input('draw'),
            'recordsTotal'    => $this->totalRecords,
            'recordsFiltered' => 0,
            'data'            => [],
            'error'           => $error ? __($error) : "Exception Message:\n\n".$exception->getMessage(),
        ]);
    }
669783
public function exceptionHandler(\Throwable $exception)
    {
        if ($exception instanceof ResponseCode) {
            try {
                $out = $this->render($exception->getCode(), [], $exception->display());
            } catch (\Throwable $exception) {
                return $this->exceptionHandler($exception);
            }

            // debug on dev / display trace
            if (!(AbstractApp::env() != AbstractApp::PRODUCTION && ob_get_length() > 0)) {
                self::response()->addHeader('Content-Type', $this->getErrorContentType());
            }

            self::response()->setStatus($exception->getCode());
            self::response()->setBody($out);
            HttpApp::instance()->end();
        } else {
            Handler::log($exception);

            if (AbstractApp::env() != AbstractApp::PRODUCTION) {
                Handler::exceptionHandler($exception);
            } else {
                $throw = new ResponseCode($exception->getMessage(), 500, $exception);
                $this->exceptionHandler($throw);
            }
        }

        return true;
    }
867985
protected function prepareException(Exception $e)
    {
        $e = parent::prepareException($e);

        if ($e instanceof MethodNotAllowedHttpException) {
            $e = new HttpException(405, 'Method not allowed', $e->getPrevious(), $e->getHeaders(), $e->getCode());
        }

        return $e;
    }
393440
protected function methodNotAllowed(string $message = "Method not allowed."): Response
    {
        return $this->getResponse()
            ->setContent($message)
            ->setStatusCode(Response::HTTP_METHOD_NOT_ALLOWED);
    }
280555
public static function getErrorResponder(Request $request, \Exception $exception)
    {
        if ($request instanceof HttpRequest) {
            return self::getHttpErrorResponder($exception, $request);
        } else {
            $requestType = get_class($request);
            throw new \InvalidArgumentException("Requests of type '{$requestType}' are not supported.");
        }
    }
36367
protected function toPrettyErrorResponse( $exception ) {
		$method = RunInterface::EXCEPTION_HANDLER;
		ob_start();
		$this->whoops->$method( $exception );
		$response = ob_get_clean();
		return Response::output( $response )->withStatus( 500 );
	}
608234
private function prepareNotAllowedResponse()
    {
        ob_clean();

        $this->response = new Response();
        $this->response->setResponseCode(ResponseCode::HTTP_METHOD_NOT_ALLOWED);

        $this->context->registerInstance($this->response);

        $this->filters->trigger(Filters::METHOD_NOT_ALLOWED, $this->context);

        $this->finalizeOutputBuffer();

        if (empty($this->response->getBody())) {
            $this->serveStaticPage('method_not_allowed');
        }
    }
120213
private function error(HttpAdapterInterface $httpAdapter, HttpAdapterException $exception)
    {
        $request = $this->getTimer()->stop($exception->getRequest());

        $this->logger->error(
            sprintf(
                'Unable to send "%s %s".',
                $exception->getRequest()->getMethod(),
                (string) $exception->getRequest()->getUri()
            ),
            [
                'adapter'   => $httpAdapter->getName(),
                'exception' => $this->getFormatter()->formatException($exception),
                'request'   => $this->getFormatter()->formatRequest($request),
                'response'  => $exception->hasResponse()
                    ? $this->getFormatter()->formatResponse($exception->getResponse())
                    : null,
            ]
        );

        return $request;
    }