getMethod() === 'OPTIONS') { $status = 200; $contentType = 'text/plain'; $output = $this->renderPlainNotAllowedMessage($methods); } else { $status = 405; $contentType = $this->determineContentType($request); switch ($contentType) { case 'application/json': $output = $this->renderJsonNotAllowedMessage($methods); break; case 'text/xml': case 'application/xml': $output = $this->renderXmlNotAllowedMessage($methods); break; case 'text/html': $output = $this->renderHtmlNotAllowedMessage($methods); break; } } $body = new Body(fopen('php://temp', 'r+')); $body->write($output); $allow = implode(', ', $methods); return $response ->withStatus($status) ->withHeader('Content-type', $contentType) ->withHeader('Allow', $allow) ->withBody($body); } /** * Determine which content type we know about is wanted using Accept header * * @param ServerRequestInterface $request * @return string */ private function determineContentType(ServerRequestInterface $request) { $acceptHeader = $request->getHeaderLine('Accept'); $selectedContentTypes = array_intersect(explode(',', $acceptHeader), $this->knownContentTypes); if (count($selectedContentTypes)) { return $selectedContentTypes[0]; } return 'text/html'; } /** * Render PLAIN not allowed message * * @param array $methods * @return string */ protected function renderPlainNotAllowedMessage($methods) { $allow = implode(', ', $methods); return 'Allowed methods: ' . $allow; } /** * Render JSON not allowed message * * @param array $methods * @return string */ protected function renderJsonNotAllowedMessage($methods) { $allow = implode(', ', $methods); return '{"message":"Method not allowed. Must be one of: ' . $allow . '"}'; } /** * Render XML not allowed message * * @param array $methods * @return string */ protected function renderXmlNotAllowedMessage($methods) { $allow = implode(', ', $methods); return "Method not allowed. Must be one of: $allow"; } /** * Render HTML not allowed message * * @param array $methods * @return string */ protected function renderHtmlNotAllowedMessage($methods) { $allow = implode(', ', $methods); $output = << Method not allowed Method not allowed Method not allowed. Must be one of: $allow
Method not allowed. Must be one of: $allow