Passed
Push — master ( 25c522...337ea3 )
by Breno
01:38
created

Cors::__invoke()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 3
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Controlabs\Handler\Slim;
4
5
use Psr\Container\ContainerInterface;
6
use Slim\Http\Request;
7
use Slim\Http\Response;
8
9
class Cors
10
{
11
    const HEADERS = [
12
        'Content-Type',
13
        'Accept',
14
        'Origin',
15
        'Authorization',
16
        'X-Requested-With'
17
    ];
18
19
    protected $container;
20
21
    public function __construct(ContainerInterface $container)
22
    {
23
        $this->container = $container;
24
    }
25
26
    public function __invoke(Request $request, Response $response, $next)
27
    {
28
        if ($next && is_callable($next)) {
29
            $response = $next($request, $response);
30
        }
31
32
        $methods = $this->methods($request);
33
34
        return $response
35
            ->withHeader('Access-Control-Allow-Origin', '*')
36
            ->withHeader('Access-Control-Allow-Headers', implode(',', self::HEADERS))
37
            ->withHeader('Access-Control-Allow-Methods', implode(',', $methods));
38
    }
39
40
    private function methods(Request $request): array
41
    {
42
        $methods = [];
43
44
        if ($route = $request->getAttribute('route')) {
45
            $pattern = $route->getPattern();
46
47
            $router = $this->container->get('router');
48
            foreach ($router->getRoutes() as $route) {
49
                if ($pattern === $route->getPattern()) {
50
                    $methods = array_merge_recursive($methods, $route->getMethods());
51
                }
52
            }
53
        } else {
54
            // Methods holds all of the HTTP Verbs that a particular route handles.
55
            $methods[] = $request->getMethod();
56
        }
57
        return $methods;
58
    }
59
}
60