PurchaseListener::onKernelRequest()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
nc 4
nop 1
dl 0
loc 14
c 0
b 0
f 0
cc 5
rs 9.6111
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\ChargeableApi\Bridge\Symfony\Bundle\Listener;
6
7
use Damax\ChargeableApi\InsufficientFunds;
8
use Damax\ChargeableApi\Processor;
9
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
10
use Symfony\Component\HttpFoundation\Response;
11
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
12
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
13
use Throwable;
14
15
class PurchaseListener
16
{
17
    private $requestMatcher;
18
    private $processor;
19
20
    public function __construct(RequestMatcherInterface $requestMatcher, Processor $processor)
21
    {
22
        $this->requestMatcher = $requestMatcher;
23
        $this->processor = $processor;
24
    }
25
26
    public function onKernelRequest(GetResponseEvent $event)
27
    {
28
        $request = $event->getRequest();
29
30
        if (!$event->isMasterRequest() || !$this->requestMatcher->matches($request)) {
31
            return;
32
        }
33
34
        try {
35
            $this->processor->processRequest($request);
36
        } catch (InsufficientFunds $e) {
37
            $event->setResponse(Response::create('', Response::HTTP_PAYMENT_REQUIRED));
38
        } catch (Throwable $e) {
39
            throw new ServiceUnavailableHttpException(null, null, $e);
40
        }
41
    }
42
}
43