Completed
Push — master ( cb269f...0b32dd )
by Arthur
02:12
created

OriginComponent::checkOrigin()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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