Passed
Pull Request — main (#11)
by Jesús
02:37
created

LnbitsBackendInvoice   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 88.89%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 56
ccs 24
cts 27
cp 0.8889
rs 10
c 2
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A requestInvoice() 0 32 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpLightning\Invoice\Domain\BackendInvoice;
6
7
use PhpLightning\Http\HttpFacadeInterface;
8
9
final class LnbitsBackendInvoice implements BackendInvoiceInterface
10
{
11
    private HttpFacadeInterface $httpFacade;
12
13
    /** @var array{api_key:string, api_endpoint:string} */
14
    private array $options;
15
16
    /**
17
     * @param array{api_key:string, api_endpoint:string} $options
18
     */
19 1
    public function __construct(
20
        HttpFacadeInterface $httpFacade,
21
        array $options,
22
    ) {
23 1
        $this->httpFacade = $httpFacade;
24 1
        $this->options = $options;
25
    }
26
27
    /**
28
     * @return array {
29
     *   status: string,
30
     *   reason: string,
31
     * }
32
     */
33 1
    public function requestInvoice(float $satsAmount, string $metadata): array
34
    {
35 1
        $endpoint = $this->options['api_endpoint'] . '/api/v1/payments';
36
37 1
        $content = [
38 1
            'out' => false,
39 1
            'amount' => $satsAmount,
40 1
            'unhashed_description' => bin2hex($metadata),
41 1
            // 'description_hash' => hash('sha256', $metadata),
42 1
        ];
43
44 1
        $response = $this->httpFacade->post($endpoint, [
45 1
            'headers' => [
46 1
                'Content-Type' => 'application/json',
47 1
                'X-Api-Key' => $this->options['api_key'],
48 1
            ],
49 1
            'body' => json_encode($content, JSON_THROW_ON_ERROR),
50 1
        ]);
51
52 1
        if ($response !== null) {
53
            /** @var array{payment_request?: string} $responseJson */
54 1
            $responseJson = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
55
56 1
            return [
57 1
                'status' => 'OK',
58 1
                'pr' => $responseJson['payment_request'] ?? 'No payment_request found',
59 1
            ];
60
        }
61
62
        return [
63
            'status' => 'ERROR',
64
            'reason' => 'Backend "LnBits" unreachable',
65
        ];
66
    }
67
}
68