LnbitsBackendInvoice::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 0
nc 1
nop 2
dl 0
loc 4
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpLightning\Invoice\Domain\BackendInvoice;
6
7
use PhpLightning\Invoice\Domain\Http\HttpApiInterface;
8
use PhpLightning\Shared\Transfer\InvoiceTransfer;
9
10
final class LnbitsBackendInvoice implements BackendInvoiceInterface
11
{
12
    /**
13
     * @param  array{api_key:string, api_endpoint:string}  $options
14
     */
15 4
    public function __construct(
16
        private readonly HttpApiInterface $httpApi,
17
        private array $options,
18
    ) {
19 4
    }
20
21 4
    public function requestInvoice(int $satsAmount, string $metadata = ''): InvoiceTransfer
22
    {
23 4
        $endpoint = $this->options['api_endpoint'] . '/api/v1/payments';
24
25 4
        $content = [
26 4
            'out' => false,
27 4
            'amount' => $satsAmount,
28 4
            'unhashed_description' => bin2hex($metadata),
29 4
            'description_hash' => hash('sha256', $metadata),
30 4
        ];
31
32 4
        $response = $this->httpApi->postRequestInvoice(
33 4
            $endpoint,
34 4
            body: json_encode($content, JSON_THROW_ON_ERROR),
35 4
            headers: [
36 4
                'Content-Type' => 'application/json',
37 4
                'X-Api-Key' => $this->options['api_key'],
38 4
            ],
39 4
        );
40
41 4
        if ($response === null) {
42 1
            return new InvoiceTransfer(status: 'ERROR', error: 'Backend "LnBits" unreachable');
43 1
        }
44 1
45
        return InvoiceTransfer::fromArray($response);
46
    }
47
}
48