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

InvoiceGenerator::generateInvoice()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 24
ccs 13
cts 13
cp 1
crap 3
rs 9.9
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