|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Slim Framework (https://slimframework.com) |
|
4
|
|
|
* |
|
5
|
|
|
* @link https://github.com/slimphp/Slim |
|
6
|
|
|
* @copyright Copyright (c) 2011-2017 Josh Lockhart |
|
7
|
|
|
* @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) |
|
8
|
|
|
*/ |
|
9
|
|
|
namespace Slim\Handlers; |
|
10
|
|
|
|
|
11
|
|
|
use Slim\Http\Body; |
|
12
|
|
|
use Slim\Handlers\Render; |
|
13
|
|
|
use UnexpectedValueException; |
|
14
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
15
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* Default Slim application not found handler. |
|
19
|
|
|
* |
|
20
|
|
|
* It outputs a simple message in either JSON, XML or HTML based on the |
|
21
|
|
|
* Accept header. |
|
22
|
|
|
*/ |
|
23
|
|
|
class NotFound extends AbstractHandler |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Invoke not found handler |
|
27
|
|
|
* |
|
28
|
|
|
* @param ServerRequestInterface $request The most recent Request object |
|
29
|
|
|
* @param ResponseInterface $response The most recent Response object |
|
30
|
|
|
* |
|
31
|
|
|
* @return ResponseInterface |
|
32
|
|
|
* @throws UnexpectedValueException |
|
33
|
|
|
*/ |
|
34
|
|
|
public function __invoke(ServerRequestInterface $request, ResponseInterface $response) |
|
35
|
|
|
{ |
|
36
|
|
|
if ($request->getMethod() === 'OPTIONS') { |
|
37
|
|
|
$contentType = 'text/plain'; |
|
38
|
|
|
$output = Render::make('PlainNotFoundOutput'); |
|
39
|
|
View Code Duplication |
} else { |
|
|
|
|
|
|
40
|
|
|
$contentType = $this->determineContentType($request); |
|
41
|
|
|
switch ($contentType) { |
|
42
|
|
|
case 'application/json': |
|
43
|
|
|
$output = Render::make('JsonNotFoundOutput'); |
|
44
|
|
|
break; |
|
45
|
|
|
|
|
46
|
|
|
case 'text/xml': |
|
47
|
|
|
case 'application/xml': |
|
48
|
|
|
$output = Render::make('XmlNotFoundOutput', $request); |
|
49
|
|
|
break; |
|
50
|
|
|
|
|
51
|
|
|
case 'text/html': |
|
52
|
|
|
$output = Render::make('HtmlNotFoundOutput', $request); |
|
53
|
|
|
break; |
|
54
|
|
|
|
|
55
|
|
|
default: |
|
56
|
|
|
throw new UnexpectedValueException('Cannot render unknown content type ' . $contentType); |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
$body = new Body(fopen('php://temp', 'r+')); |
|
61
|
|
|
$body->write($output); |
|
62
|
|
|
|
|
63
|
|
|
return $response->withStatus(404) |
|
64
|
|
|
->withHeader('Content-Type', $contentType) |
|
65
|
|
|
->withBody($body); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.