TransactionLogger::flush()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
1
<?php
2
3
namespace Loevgaard\DandomainAltapayBundle\Http;
4
5
use Loevgaard\DandomainAltapayBundle\Entity\HttpTransaction;
6
use Loevgaard\DandomainAltapayBundle\Entity\HttpTransactionRepository;
7
use Symfony\Component\HttpFoundation\Request;
8
use Symfony\Component\HttpFoundation\Response;
9
10
class TransactionLogger
11
{
12
    /**
13
     * @var array
14
     */
15
    private $transactions;
16
17
    /**
18
     * @var HttpTransactionRepository
19
     */
20
    private $httpTransactionRepository;
21
22
    public function __construct(HttpTransactionRepository $httpTransactionRepository)
23
    {
24
        $this->transactions = [];
25
        $this->httpTransactionRepository = $httpTransactionRepository;
26
    }
27
28
    public function setRequest(Request $request)
29
    {
30
        $requestHash = $this->hashRequest($request);
31
32
        $this->transactions[$requestHash] = [
33
            'request' => $request,
34
            'response' => null,
35
        ];
36
    }
37
38
    public function setResponse(Request $request, Response $response)
39
    {
40
        $requestHash = $this->hashRequest($request);
41
42
        // if the request hash is set it means we have a corresponding request
43
        // which means we want to log it
44
        if (isset($this->transactions[$requestHash])) {
45
            $this->transactions[$requestHash]['response'] = $response;
46
        }
47
    }
48
49
    /**
50
     * Flushes the HTTP transaction log.
51
     */
52
    public function flush()
53
    {
54
        foreach ($this->transactions as $transaction) {
55
            $entity = new HttpTransaction();
56
            $entity->setRequest($transaction['request'])
57
                ->setResponse((string) $transaction['response']);
58
59
            $this->httpTransactionRepository->save($entity);
60
        }
61
    }
62
63
    /**
64
     * @param Request $request
65
     *
66
     * @return string
67
     */
68
    private function hashRequest(Request $request)
69
    {
70
        return spl_object_hash($request);
71
    }
72
}
73