1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Zemit Framework. |
4
|
|
|
* |
5
|
|
|
* (c) Zemit Team <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE.txt |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Zemit\Mvc\Dispatcher; |
12
|
|
|
|
13
|
|
|
use Phalcon\Events\Event; |
14
|
|
|
use Phalcon\Http\Response; |
15
|
|
|
use Zemit\Bootstrap\Config; |
16
|
|
|
use Zemit\Di\Injectable; |
17
|
|
|
use Zemit\Dispatcher\DispatcherInterface; |
18
|
|
|
use Zemit\Http\Request; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Class Preflight |
22
|
|
|
*/ |
23
|
|
|
class Preflight extends Injectable |
24
|
|
|
{ |
25
|
|
|
/** |
26
|
|
|
* @param Event $event |
27
|
|
|
* @param DispatcherInterface $dispatcher |
28
|
|
|
*/ |
29
|
|
|
public function beforeExecuteRoute(Event $event, DispatcherInterface $dispatcher) |
|
|
|
|
30
|
|
|
{ |
31
|
|
|
$di = $dispatcher->getDI(); |
|
|
|
|
32
|
|
|
|
33
|
|
|
/** @var Response $response */ |
34
|
|
|
$response = $di->get('response'); |
35
|
|
|
|
36
|
|
|
/** @var Request $request */ |
37
|
|
|
$request = $di->get('request'); |
38
|
|
|
|
39
|
|
|
if ($request->isCors()) { |
40
|
|
|
|
41
|
|
|
/** @var Config $request */ |
42
|
|
|
$config = $di->get('config'); |
43
|
|
|
|
44
|
|
|
$this->setCorsHeaders($response, |
45
|
|
|
$request->getHeader('Origin'), |
46
|
|
|
$config->path('response.corsHeaders', [])->toArray() |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if ($request->isPreflight()) { |
51
|
|
|
$this->sendNoContent($response); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function setCorsHeaders(Response $response, string $origin, array $headers = []) |
56
|
|
|
{ |
57
|
|
|
// Set default cors headers |
58
|
|
|
if (!empty($headers)) { |
59
|
|
|
foreach ($headers as $headerKey => $headerValue) { |
60
|
|
|
if (!$response->hasHeader($headerKey) && !is_array($headerValue)) { |
61
|
|
|
$response->setHeader($headerKey, $headerValue); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// Set default origin value if allowed |
67
|
|
|
$originKey = 'Access-Control-Allow-Origin'; |
68
|
|
|
if (!$response->hasHeader($originKey) |
69
|
|
|
&& is_array($headers[$originKey]) |
70
|
|
|
&& in_array($origin, $headers[$originKey]) |
71
|
|
|
) { |
72
|
|
|
$response->setHeader($originKey, $origin); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* Send 204 no content response & exit application |
78
|
|
|
* @param Response $response |
79
|
|
|
* @return void |
80
|
|
|
*/ |
81
|
|
|
public function sendNoContent(Response $response) |
82
|
|
|
{ |
83
|
|
|
$response->setStatusCode(204)->send(); |
84
|
|
|
exit; |
|
|
|
|
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.