Passed
Push — master ( 184cb3...5f1713 )
by Waaaaaaaaaa
02:19
created

Sender   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 61
ccs 0
cts 30
cp 0
rs 10
c 0
b 0
f 0
wmc 8

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getEndpoint() 0 3 1
A send() 0 15 2
A setScheme() 0 3 1
A setHost() 0 3 1
A setCurlOptions() 0 11 1
A __construct() 0 3 1
A sendAsync() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Logfile;
4
5
class Sender
6
{
7
    protected $host = 'logfile.co';
8
9
    protected $scheme = 'https';
10
11
    protected $timeout;
12
13
    public function __construct(int $timeout = 2)
14
    {
15
        $this->timeout = $timeout;
16
    }
17
18
    public function setHost($host): void
19
    {
20
        $this->host = $host;
21
    }
22
23
    public function setScheme($scheme): void
24
    {
25
        $this->scheme = $scheme;
26
    }
27
28
    public function send(Payload $payload, string $token): bool
29
    {
30
        $handle = \curl_init();
31
32
        if (!is_resource($handle)) {
33
            throw new \ErrorException('Failed to start curl session');
34
        }
35
36
        $this->setCurlOptions($handle, $payload, $token);
37
38
        $result = \curl_exec($handle);
39
40
        \curl_close($handle);
41
42
        return $result !== false;
43
    }
44
45
    public function sendAsync(Payload $payload, string $token)
46
    {
47
        `curl -H 'Content-Type: application/json' -m {$this->timeout} -d '{$payload->getEncodedData()}' {$this->getEndpoint($token)} > /dev/null 2>&1 &`;
48
    }
49
50
    protected function getEndpoint(string $token): string
51
    {
52
        return \sprintf('%s://%s/api/push/%s', $this->scheme, $this->host, $token);
53
    }
54
55
    protected function setCurlOptions($handle, Payload $payload, string $token): void
56
    {
57
        \curl_setopt_array($handle, [
58
            CURLOPT_URL => $this->getEndpoint($token),
59
            CURLOPT_POST => true,
60
            CURLOPT_POSTFIELDS => $payload->getEncodedData(),
61
            CURLOPT_HTTPHEADER => [
62
                'Content-Type: application/json',
63
            ],
64
            CURLOPT_RETURNTRANSFER => true,
65
            CURLOPT_TIMEOUT => $this->timeout,
66
        ]);
67
    }
68
}
69