Passed
Push — main ( 36fa87...8ed71a )
by Chema
01:06 queued 13s
created

InvoiceGenerator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 24
c 0
b 0
f 0
dl 0
loc 56
ccs 30
cts 30
cp 1
rs 10
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A errorResponse() 0 5 1
A __construct() 0 5 1
A okResponse() 0 11 1
A generateInvoice() 0 24 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpLightning\Invoice\Domain\LnAddress;
6
7
use PhpLightning\Invoice\Domain\BackendInvoice\BackendInvoiceInterface;
8
use PhpLightning\Invoice\Domain\Transfer\SendableRange;
9
10
final class InvoiceGenerator
11
{
12
    public const MESSAGE_PAYMENT_RECEIVED = 'Payment received!';
13
14 3
    public function __construct(
15
        private BackendInvoiceInterface $backendInvoice,
16
        private SendableRange $sendableRange,
17
        private string $lnAddress,
18
    ) {
19 3
    }
20
21 3
    public function generateInvoice(int $milliSats): array
22
    {
23 3
        if (!$this->sendableRange->contains($milliSats)) {
24 1
            return [
25 1
                'status' => 'ERROR',
26 1
                'reason' => 'Amount is not between minimum and maximum sendable amount',
27 1
            ];
28
        }
29
        // Modify the description if you want to custom it
30
        // This will be the description on the wallet that pays your ln address
31
        // TODO: Make this customizable from some external configuration file
32 2
        $description = 'Pay to ' . $this->lnAddress;
33
34
        // TODO: images not implemented yet
35 2
        $imageMetadata = '';
36 2
        $metadata = '[["text/plain","' . $description . '"],["text/identifier","' . $this->lnAddress . '"]' . $imageMetadata . ']';
37
38 2
        $invoice = $this->backendInvoice->requestInvoice($milliSats / 1000, $metadata);
39
40 2
        if ($invoice['status'] === 'OK') {
41 1
            return $this->okResponse($invoice);
42
        }
43
44 1
        return $this->errorResponse($invoice);
45
    }
46
47 1
    private function okResponse(array $invoice): array
48
    {
49 1
        return [
50 1
            'pr' => $invoice['pr'],
51 1
            'status' => 'OK',
52 1
            'successAction' => [
53 1
                'tag' => 'message',
54 1
                'message' => self::MESSAGE_PAYMENT_RECEIVED,
55 1
            ],
56 1
            'routes' => [],
57 1
            'disposable' => false,
58 1
        ];
59
    }
60
61 1
    private function errorResponse(array $invoice): array
62
    {
63 1
        return [
64 1
            'status' => $invoice['status'],
65 1
            'reason' => $invoice['reason'],
66 1
        ];
67
    }
68
}
69