|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Chubbyphp\Cors; |
|
6
|
|
|
|
|
7
|
|
|
use Chubbyphp\Cors\Negotiation\Origin\OriginNegotiatorInterface; |
|
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
10
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
11
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
12
|
|
|
|
|
13
|
|
|
final class CorsMiddleware implements MiddlewareInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var OriginNegotiatorInterface |
|
17
|
|
|
*/ |
|
18
|
|
|
private $originNegotiator; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var bool |
|
22
|
|
|
*/ |
|
23
|
|
|
private $allowCredentials; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var array |
|
27
|
|
|
*/ |
|
28
|
|
|
private $exposeHeaders; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param OriginNegotiatorInterface $originNegotiator |
|
32
|
|
|
* @param bool $allowCredentials |
|
33
|
|
|
* @param array $exposeHeaders |
|
34
|
|
|
*/ |
|
35
|
3 |
|
public function __construct( |
|
36
|
|
|
OriginNegotiatorInterface $originNegotiator, |
|
37
|
|
|
bool $allowCredentials = false, |
|
38
|
|
|
array $exposeHeaders = [] |
|
39
|
|
|
) { |
|
40
|
3 |
|
$this->originNegotiator = $originNegotiator; |
|
41
|
3 |
|
$this->allowCredentials = $allowCredentials; |
|
42
|
3 |
|
$this->exposeHeaders = $exposeHeaders; |
|
43
|
3 |
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param ServerRequestInterface $request |
|
47
|
|
|
* @param RequestHandlerInterface $handler |
|
48
|
|
|
* |
|
49
|
|
|
* @return ResponseInterface |
|
50
|
|
|
*/ |
|
51
|
3 |
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface |
|
52
|
|
|
{ |
|
53
|
3 |
|
$allowOrigin = $this->originNegotiator->negotiate($request); |
|
54
|
|
|
|
|
55
|
3 |
|
$request = $request->withAttribute('allowOrigin', $allowOrigin); |
|
56
|
|
|
|
|
57
|
3 |
|
$response = $handler->handle($request); |
|
58
|
|
|
|
|
59
|
3 |
|
if (null !== $allowOrigin) { |
|
60
|
|
|
$response = $response |
|
61
|
2 |
|
->withHeader('Access-Control-Allow-Origin', $allowOrigin) |
|
62
|
2 |
|
->withHeader('Access-Control-Allow-Credentials', $this->allowCredentials ? 'true' : 'false') |
|
63
|
2 |
|
->withHeader('Access-Control-Expose-Headers', implode(', ', $this->exposeHeaders)) |
|
64
|
|
|
; |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
3 |
|
return $response; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|