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

Sender::setScheme()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
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