1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace TH\Silex\CORS; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use Silex\Api\BootableProviderInterface; |
7
|
|
|
use Silex\Application; |
8
|
|
|
use Symfony\Component\HttpFoundation\Request; |
9
|
|
|
use Symfony\Component\HttpFoundation\Response; |
10
|
|
|
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; |
11
|
|
|
use Pimple\Container; |
12
|
|
|
use Pimple\ServiceProviderInterface; |
13
|
|
|
use TH\Silex\CORS\CORSMiddleware; |
14
|
|
|
|
15
|
|
|
class CORSProvider implements BootableProviderInterface, ServiceProviderInterface |
16
|
|
|
{ |
17
|
|
|
public function register(Container $container) |
18
|
|
|
{ |
19
|
|
|
$container["cors.origin"] = "*"; |
20
|
|
|
$container["cors.methods"] = ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"]; |
21
|
|
|
$container["cors.headers"] = ["Authorization", "Content-Type"]; |
22
|
|
|
$container["cors.middleware"] = function (Container $container) { |
23
|
|
|
return new CORSMiddleware( |
24
|
|
|
$container["cors.origin"], |
25
|
|
|
$container["cors.methods"], |
26
|
|
|
$container["cors.headers"] |
27
|
|
|
); |
28
|
|
|
}; |
29
|
|
|
$container["cors.exception_handler"] = $container->protect( |
30
|
|
|
function (Exception $e, Request $request, $code) use ($container) { |
31
|
|
|
if ($e instanceof MethodNotAllowedHttpException && $request->getmethod() === Request::METHOD_OPTIONS) { |
32
|
|
|
return $container["cors.middleware"]( |
33
|
|
|
$request, |
34
|
|
|
new Response("", Response::HTTP_NO_CONTENT, ["X-Status-Code" => Response::HTTP_NO_CONTENT]) |
35
|
|
|
); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function boot(Application $app) |
42
|
|
|
{ |
43
|
|
|
$app->after($app["cors.middleware"]); |
44
|
|
|
$app->error($app["cors.exception_handler"], 0); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|