Passed
Pull Request — main (#10)
by Chema
02:14
created

LnbitsBackendInvoice::requestInvoice()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 2.0078

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 18
nc 2
nop 2
dl 0
loc 30
ccs 21
cts 24
cp 0.875
crap 2.0078
rs 9.6666
c 2
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
9
final class LnbitsBackendInvoice implements BackendInvoiceInterface
10
{
11
    /**
12
     * @param array{api_key:string, api_endpoint:string} $options
13
     */
14 1
    public function __construct(
15
        private HttpApiInterface $httpApi,
16
        private array $options,
17
    ) {
18 1
    }
19
20
    /**
21
     * @return array {
22
     *   status: string,
23
     *   reason: string,
24
     * }
25
     */
26 1
    public function requestInvoice(float $satsAmount, string $metadata): array
27
    {
28 1
        $endpoint = $this->options['api_endpoint'] . '/api/v1/payments';
29
30 1
        $content = [
31 1
            'out' => false,
32 1
            'amount' => $satsAmount,
33 1
            'unhashed_description' => bin2hex($metadata),
34 1
            // 'description_hash' => hash('sha256', $metadata),
35 1
        ];
36
37 1
        $response = $this->httpApi->postRequestInvoice(
38 1
            $endpoint,
39 1
            body: json_encode($content, JSON_THROW_ON_ERROR),
40 1
            headers: [
41 1
                'Content-Type' => 'application/json',
42 1
                'X-Api-Key' => $this->options['api_key'],
43 1
            ],
44 1
        );
45
46 1
        if ($response !== null) {
47 1
            return [
48 1
                'status' => 'OK',
49 1
                'pr' => $response['payment_request'] ?? 'No payment_request found',
50 1
            ];
51
        }
52
53
        return [
54
            'status' => 'ERROR',
55
            'reason' => 'Backend "LnBits" unreachable',
56
        ];
57
    }
58
}
59