OriginComponent::sendAndClose()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace WSSC\Components;
4
5
/**
6
 * Class OriginComponent
7
 * @package WSSC\Components
8
 */
9
class OriginComponent
10
{
11
    /**
12
     * @var false|resource
13
     */
14
    private $client;
15
16
17
    /**
18
     * @var ServerConfig
19
     */
20
    private ServerConfig $config;
21
22
    /**
23
     * OriginComponent constructor.
24
     * @param ServerConfig $config
25
     * @param false|resource $client
26
     */
27
    public function __construct(ServerConfig $config, $client)
28
    {
29
        $this->config = $config;
30
        $this->client = $client;
31
    }
32
33
    /**
34
     * Checks if there is a compatible origin header came from client
35
     * @param string $headers
36
     * @return bool
37
     * @throws \Exception
38
     */
39
    public function checkOrigin(string $headers): bool
40
    {
41
        preg_match('/Origin\:\s(.*?)\s/', $headers, $matches);
42
        if (empty($matches[1])) {
43
            $this->sendAndClose('No Origin header found.');
44
            return false;
45
        }
46
47
        $originHost = $matches[1];
48
        $allowedOrigins = $this->config->getOrigins();
49
        if (in_array($originHost, $allowedOrigins, true) === false) {
50
            $this->sendAndClose('Host ' . $originHost . ' is not allowed to pass access control as origin.');
51
            return false;
52
        }
53
54
        return true;
55
    }
56
57
    /**
58
     * @param string $msg
59
     * @throws \Exception
60
     */
61
    private function sendAndClose(string $msg): void
62
    {
63
        $conn = new Connection($this->client);
64
        $conn->send($msg);
65
        $conn->close();
66
    }
67
}