Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
cors.php
1<?php
2
4
6
12final class Cors extends Base
13{
15 private ?string $origin;
16
18 private bool $credentials;
19
20 private ?array $allowedMethods;
21 private ?array $allowedHeaders;
22
29 public function __construct(string $origin = null, bool $credentials = false)
30 {
31 $this->origin = $origin;
32 $this->credentials = $credentials;
33
34 parent::__construct();
35 }
36
37 public function onBeforeAction(Main\Event $event): void
38 {
39 $this->setCorsHeaders();
40 }
41
42 public function onAfterAction(Main\Event $event): void
43 {
44 $this->setCorsHeaders();
45 }
46
47 public function setAllowedMethods(array $methods): self
48 {
49 $this->allowedMethods = $methods;
50 return $this;
51 }
52
53 public function setAllowedHeaders(array $headers): self
54 {
55 $this->allowedHeaders = $headers;
56 return $this;
57 }
58
59 private function setCorsHeaders(): void
60 {
61 $context = Main\Context::getCurrent();
62 if (!$context)
63 {
64 return;
65 }
66
67 $response = $context->getResponse();
68 $origin = $this->origin ?: $context->getRequest()->getHeader('Origin');
69 if ($origin && $response instanceof Main\HttpResponse)
70 {
71 $currentHttpHeaders = $response->getHeaders();
72 if (!$currentHttpHeaders->get('Access-Control-Allow-Origin'))
73 {
74 $currentHttpHeaders->add('Access-Control-Allow-Origin', $origin);
75 }
76 if ($this->credentials && !$currentHttpHeaders->get('Access-Control-Allow-Credentials'))
77 {
78 $currentHttpHeaders->add('Access-Control-Allow-Credentials', 'true');
79 }
80 if (!empty($this->allowedHeaders) && !$currentHttpHeaders->get('Access-Control-Allow-Headers'))
81 {
82 $currentHttpHeaders->add('Access-Control-Allow-Headers', implode(',', $this->allowedHeaders));
83 }
84 if (!empty($this->allowedMethods) && !$currentHttpHeaders->get('Access-Control-Allow-Methods'))
85 {
86 $currentHttpHeaders->add('Access-Control-Allow-Methods', implode(',', $this->allowedMethods));
87 }
88 }
89 }
90}
__construct(string $origin=null, bool $credentials=false)
Definition cors.php:29
onAfterAction(Main\Event $event)
Definition cors.php:42
onBeforeAction(Main\Event $event)
Definition cors.php:37
setAllowedHeaders(array $headers)
Definition cors.php:53
setAllowedMethods(array $methods)
Definition cors.php:47