Sender   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 8
eloc 29
dl 0
loc 67
ccs 0
cts 35
cp 0
rs 10
c 4
b 0
f 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A setScheme() 0 3 1
A setHost() 0 3 1
A send() 0 15 2
A __construct() 0 3 1
A getEndpoint() 0 3 1
A setCurlOptions() 0 11 1
A sendAsync() 0 8 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
        shell_exec(sprintf(
48
            'curl -H %s -m %u -d %s %s > /dev/null 2>&1 &',
49
            escapeshellarg('Content-Type: application/json'),
50
            $this->timeout,
51
            escapeshellarg($payload->getEncodedData()),
52
            escapeshellarg($this->getEndpoint($token))
53
        ));
54
    }
55
56
    protected function getEndpoint(string $token): string
57
    {
58
        return \sprintf('%s://%s/api/push/%s', $this->scheme, $this->host, $token);
59
    }
60
61
    protected function setCurlOptions($handle, Payload $payload, string $token): void
62
    {
63
        \curl_setopt_array($handle, [
64
            CURLOPT_URL => $this->getEndpoint($token),
65
            CURLOPT_POST => true,
66
            CURLOPT_POSTFIELDS => $payload->getEncodedData(),
67
            CURLOPT_HTTPHEADER => [
68
                'Content-Type: application/json',
69
            ],
70
            CURLOPT_RETURNTRANSFER => true,
71
            CURLOPT_TIMEOUT => $this->timeout,
72
        ]);
73
    }
74
}
75