|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of Flight Routing. |
|
7
|
|
|
* |
|
8
|
|
|
* PHP version 7.1 and above required |
|
9
|
|
|
* |
|
10
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
|
11
|
|
|
* @copyright 2019 Biurad Group (https://biurad.com/) |
|
12
|
|
|
* @license https://opensource.org/licenses/BSD-3-Clause License |
|
13
|
|
|
* |
|
14
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
15
|
|
|
* file that was distributed with this source code. |
|
16
|
|
|
*/ |
|
17
|
|
|
|
|
18
|
|
|
namespace Flight\Routing\Middlewares; |
|
19
|
|
|
|
|
20
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
21
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
22
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
23
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Fix Content-Type. |
|
27
|
|
|
* |
|
28
|
|
|
* @author Divine Niiquaye Ibok <[email protected]> |
|
29
|
|
|
*/ |
|
30
|
|
|
class ContentTypeMiddleware implements MiddlewareInterface |
|
31
|
|
|
{ |
|
32
|
|
|
/** |
|
33
|
|
|
* @param ServerRequestInterface $request |
|
34
|
|
|
* @param RequestHandlerInterface $handler |
|
35
|
|
|
* |
|
36
|
|
|
* @return ResponseInterface |
|
37
|
|
|
*/ |
|
38
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
39
|
|
|
{ |
|
40
|
|
|
if ( |
|
41
|
|
|
!$request->hasHeader('Content-Type') && |
|
42
|
|
|
\in_array($request->getMethod(), ['POST', 'PUT', 'DELETE'], true) |
|
43
|
|
|
) { |
|
44
|
|
|
$request = $request->withAttribute('Content-Type', 'application/x-www-form-urlencoded'); |
|
45
|
|
|
} |
|
46
|
|
|
$formContentType = ['application/x-www-form-urlencoded', 'multipart/form-data']; |
|
47
|
|
|
|
|
48
|
|
|
if ( |
|
49
|
|
|
$request->getMethod() === 'POST' && |
|
50
|
|
|
\in_array($request->getHeaderLine('Content-Type'), $formContentType, true) |
|
51
|
|
|
) { |
|
52
|
|
|
$request = $request->withParsedBody($_POST); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** @var ResponseInterface $response */ |
|
56
|
|
|
$response = $handler->handle($request); |
|
57
|
|
|
|
|
58
|
|
|
// Fix Content-Type |
|
59
|
|
|
if (!$response->hasHeader('Content-Type')) { |
|
60
|
|
|
$response = $response |
|
61
|
|
|
->withHeader('Content-Type', 'text/html; charset=UTF-8'); |
|
62
|
|
|
} elseif ( |
|
63
|
|
|
0 === \stripos($response->getHeaderLine('Content-Type'), 'text/') && |
|
64
|
|
|
false === \stripos($response->getHeaderLine('Content-Type'), 'charset') |
|
65
|
|
|
) { |
|
66
|
|
|
// add the charset |
|
67
|
|
|
$response = $response |
|
68
|
|
|
->withHeader('Content-Type', $response->getHeaderLine('Content-Type') . '; charset=UTF-8'); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return $response; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|