Completed
Push — master ( 7c1eaa...80d841 )
by Joachim
15:53
created

TransactionLogger   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 2
dl 0
loc 63
c 0
b 0
f 0
rs 10

5 Methods

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