PurchaseListener   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 25
c 0
b 0
f 0
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelRequest() 0 14 5
A __construct() 0 4 1
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