Passed
Push — main ( 007292...47f9cf )
by Chema
02:25
created

InvoiceController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpLightning\Invoice\Infrastructure\Controller;
6
7
use Gacela\Framework\DocBlockResolverAwareTrait;
8
use Gacela\Router\Entities\Request;
9
use PhpLightning\Invoice\InvoiceFacade;
10
use Throwable;
11
12
/**
13
 * @method InvoiceFacade getFacade()
14
 */
15
final class InvoiceController
16
{
17
    use DocBlockResolverAwareTrait;
18
19
    public function __construct(
20
        private Request $request,
21
    ) {
22
    }
23
24
    /**
25
     * @psalm-suppress InternalMethod
26
     */
27
    public function __invoke(string $username = '', int $amount = 0): string
28
    {
29
        try {
30
            if ($amount === 0) {
31
                $amount = (int)$this->request->get('amount');
32
            }
33
34
            if ($amount === 0) {
35
                return $this->json(
36
                    $this->getFacade()->getCallbackUrl($username),
37
                );
38
            }
39
40
            return $this->json(
41
                $this->getFacade()->generateInvoice($username, $amount),
42
            );
43
        } catch (Throwable $e) {
44
            return $this->error($e);
45
        }
46
    }
47
48
    private function json(array $json): string
49
    {
50
        return json_encode($json, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
51
    }
52
53
    private function error(Throwable $e): string
54
    {
55
        return $this->json([
56
            'status' => 'ERROR',
57
            'message' => $e->getMessage(),
58
        ]);
59
    }
60
}
61