Completed
Pull Request — master (#2)
by Breno
01:30
created

Cors::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
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
        $route = $request->getAttribute('route');
29
30
        $methods = [];
31
        if (empty($route)) {
32
            // Methods holds all of the HTTP Verbs that a particular route handles.
33
            $methods[] = $request->getMethod();
34
        } else {
35
            $pattern = $route->getPattern();
36
37
            $router = $this->container->get('router');
38
            foreach ($router->getRoutes() as $route) {
39
                if ($pattern === $route->getPattern()) {
40
                    $methods = array_merge_recursive($methods, $route->getMethods());
41
                }
42
            }
43
        }
44
45
        if ($next && is_callable($next)) {
46
            $response = $next($request, $response);
47
        }
48
49
        return $response
50
            ->withHeader('Access-Control-Allow-Origin', '*')
51
            ->withHeader('Access-Control-Allow-Headers', implode(',', self::HEADERS))
52
            ->withHeader('Access-Control-Allow-Methods', implode(',', $methods));
53
    }
54
}
55