1
|
|
|
<?php |
2
|
|
|
namespace Eko3alpha\Slim\Middleware; |
3
|
|
|
|
4
|
|
|
use Psr\Http\Message\RequestInterface; |
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
|
7
|
|
|
class CorsMiddleware |
8
|
|
|
{ |
9
|
|
|
protected $cors; |
10
|
|
|
|
11
|
|
|
public function __construct($cors) |
12
|
|
|
{ |
13
|
|
|
$this->cors = $cors; |
14
|
|
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Middleware invokable class |
18
|
|
|
* |
19
|
|
|
* @param RequestInterface $request PSR7 request |
20
|
|
|
* @param ResponseInterface $response PSR7 response |
21
|
|
|
* @param callable $next Next middleware |
22
|
|
|
* |
23
|
|
|
* @return ResponseInterface |
24
|
|
|
*/ |
25
|
|
|
public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) |
|
|
|
|
26
|
|
|
{ |
27
|
|
|
$response = $next($request, $response); |
28
|
|
|
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : 'none'; |
29
|
|
|
return $this->getResponse($response, $origin, $this->cors); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Gets allow method string |
34
|
|
|
* @param array $cors access list with methods |
35
|
|
|
* @param string $origin origin domain |
36
|
|
|
* @return string comma delimited string of methods |
37
|
|
|
*/ |
38
|
|
|
private function getAllowedMethodsString($cors, $origin) |
39
|
|
|
{ |
40
|
|
|
$methods = $cors[$origin]; |
41
|
|
|
if (is_array($methods)) { |
42
|
|
|
$methods = implode(', ', $methods); |
43
|
|
|
} |
44
|
|
|
return $methods; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Gets the proper origin header value |
49
|
|
|
* @param array $cors cors config |
50
|
|
|
* @param string $origin http_origin |
51
|
|
|
* @return string origin value |
52
|
|
|
*/ |
53
|
|
|
private function getOriginHeader($cors, $origin) |
54
|
|
|
{ |
55
|
|
|
if (isset($cors['*'])) { |
56
|
|
|
return '*'; |
57
|
|
|
} |
58
|
|
|
return $origin; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Gets appropriate response object |
63
|
|
|
* @param ResponseInterface $response PSR7 Response |
64
|
|
|
* @param string $origin origin domain |
65
|
|
|
* @param array $cors access list with methods |
66
|
|
|
* @return ResponseInterface PSR7 Response |
67
|
|
|
*/ |
68
|
|
|
private function getResponse(ResponseInterface $response, $origin, $cors) |
69
|
|
|
{ |
70
|
|
|
|
71
|
|
|
if (isset($cors['*'])) { |
72
|
|
|
$origin = '*'; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
if (!isset($cors[$origin])) { |
76
|
|
|
return $response; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
return $response |
80
|
|
|
->withHeader('Access-Control-Allow-Origin', $this->getOriginHeader($cors, $origin)) |
81
|
|
|
->withHeader('Access-Control-Allow-Methods', $this->getAllowedMethodsString($cors, $origin)); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: