Api::sendReportsInBatches()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Facade\FlareClient;
4
5
use Facade\FlareClient\Http\Client;
6
use Facade\FlareClient\Truncation\ReportTrimmer;
7
8
class Api
9
{
10
    /** @var \Facade\FlareClient\Http\Client */
11
    private $client;
12
13
    /** @var bool */
14
    public static $sendInBatches = true;
15
16
    /** @var array */
17
    private $queue = [];
18
19
    public function __construct(Client $client)
20
    {
21
        $this->client = $client;
22
23
        register_shutdown_function([$this, 'sendQueuedReports']);
24
    }
25
26
    public static function sendReportsInBatches(bool $batchSending = true)
27
    {
28
        static::$sendInBatches = $batchSending;
29
    }
30
31
    public function report(Report $report)
32
    {
33
        try {
34
            if (static::$sendInBatches) {
35
                $this->addReportToQueue($report);
36
            } else {
37
                $this->sendReportToApi($report);
38
            }
39
        } catch (\Exception $e) {
40
            //
41
        }
42
    }
43
44
    public function sendTestReport(Report $report)
45
    {
46
        $this->sendReportToApi($report);
47
    }
48
49
    private function addReportToQueue(Report $report)
50
    {
51
        $this->queue[] = $report;
52
    }
53
54
    public function sendQueuedReports()
55
    {
56
        try {
57
            foreach ($this->queue as $report) {
58
                $this->sendReportToApi($report);
59
            }
60
        } catch (\Exception $e) {
61
            //
62
        } finally {
63
            $this->queue = [];
64
        }
65
    }
66
67
    private function sendReportToApi(Report $report)
68
    {
69
        $this->client->post('reports', $this->truncateReport($report->toArray()));
70
    }
71
72
    private function truncateReport(array $payload): array
73
    {
74
        return (new ReportTrimmer())->trim($payload);
75
    }
76
}
77