|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Controlabs\Handler\Slim; |
|
4
|
|
|
|
|
5
|
|
|
use FastRoute\Dispatcher; |
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
|
7
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
|
8
|
|
|
use Slim\Router; |
|
9
|
|
|
|
|
10
|
|
|
class Cors |
|
11
|
|
|
{ |
|
12
|
|
|
const HEADERS = [ |
|
13
|
|
|
'Content-Type', |
|
14
|
|
|
'Accept', |
|
15
|
|
|
'Origin', |
|
16
|
|
|
'Authorization', |
|
17
|
|
|
'X-Requested-With' |
|
18
|
|
|
]; |
|
19
|
|
|
|
|
20
|
|
|
protected $container; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct($container) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->container = $container; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function __invoke(Request $request, Response $response, $next) |
|
28
|
|
|
{ |
|
29
|
|
|
if ($next && is_callable($next)) { |
|
30
|
|
|
$response = $next($request, $response); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
return $response |
|
34
|
|
|
->withHeader('Access-Control-Allow-Origin', '*') |
|
35
|
|
|
->withHeader('Access-Control-Allow-Headers', implode(',', self::HEADERS)) |
|
36
|
|
|
->withHeader('Access-Control-Allow-Methods', implode(',', $this->methods($request))); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
protected function methods(Request $request) |
|
40
|
|
|
{ |
|
41
|
|
|
$methods = $this->optionsMethods($request); |
|
42
|
|
|
|
|
43
|
|
|
$currentRoute = $request->getAttribute('route'); |
|
44
|
|
|
|
|
45
|
|
|
if (empty($currentRoute)) { |
|
46
|
|
|
return array_merge($methods, [$request->getMethod()]); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
$pattern = $currentRoute->getPattern(); |
|
50
|
|
|
|
|
51
|
|
|
foreach ($this->router()->getRoutes() as $route) { |
|
52
|
|
|
$pattern === $route->getPattern() |
|
53
|
|
|
and $methods = array_merge_recursive($methods, $route->getMethods()); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $methods; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
protected function optionsMethods(Request $request) |
|
60
|
|
|
{ |
|
61
|
|
|
if ('OPTIONS' !== $request->getMethod()) { |
|
62
|
|
|
return []; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
list($status, $allowedMethods) = $this->router()->dispatch($request); |
|
66
|
|
|
|
|
67
|
|
|
return Dispatcher::METHOD_NOT_ALLOWED == $status ? $allowedMethods : []; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
protected function router(): Router |
|
71
|
|
|
{ |
|
72
|
|
|
return $this->container->get('router'); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
|