Completed
Push — feature/EVO-7278-tracking-info... ( cdfec3...e99586 )
by
unknown
11:49 queued 05:41
created

StoreManager::trackEvent()   A

Complexity

Conditions 2
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 11
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 3
nop 3
crap 6
1
<?php
2
/**
3
 * To manage the data to be saved into DB as last thing to do.
4
 */
5
namespace Graviton\AuditTrackingBundle\Manager;
6
7
use Doctrine\ODM\MongoDB\DocumentManager;
8
use Graviton\AuditTrackingBundle\Document\AuditTracking;
9
use Doctrine\Bundle\MongoDBBundle\ManagerRegistry;
10
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
11
12
/**
13
 * Class StoreManager
14
 * @package Graviton\AuditTrackingBundle\Manager
15
 *
16
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
17
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
18
 * @link     http://swisscom.ch
19
 */
20
class StoreManager
21
{
22
    const AUDIT_HEADER_KEY = 'x-header-audit-thread';
23
24
    /** @var ActivityManager */
25
    private $activityManager;
26
27
    /** @var DocumentManager */
28
    private $documentManager;
29
30
    /**
31
     * StoreManager constructor.
32
     * @param ActivityManager $activityManager Main activity manager
33
     * @param ManagerRegistry $doctrine        Doctrine document mapper
34
     */
35
    public function __construct(
36
        ActivityManager $activityManager,
37
        ManagerRegistry $doctrine
38
    ) {
39
        $this->activityManager = $activityManager;
40
41
        $this->documentManager = $doctrine->getManager();
42
    }
43
44
    /**
45
     * Save data to DB
46
     * onKernelResponse
47
     *
48
     * @param FilterResponseEvent $event Sf fired kernel event
49
     *
50
     * @return void
51
     */
52
    public function persistEvents(FilterResponseEvent $event)
53
    {
54
        $events = $this->activityManager->getEvents();
55
        if (!$events) {
56
            return;
57
        }
58
59
        $thread = $this->generateUUID();
60
        $username = $this->activityManager->getSecurityUsername();
61
        
62
        // If request is valid we save it or we do not.
63
        if (!$this->activityManager->getConfigValue('log_on_failure', 'bool')) {
64
            $response = $event->getResponse();
65
            if (!$response->isSuccessful()) {
66
                // TODO log that we do not save
67
                return;
68
            }
69
        }
70
71
        // Set Audit header information
72
        $response->headers->set(self::AUDIT_HEADER_KEY, $thread);
73
74
        foreach ($events as $event) {
75
            $this->trackEvent($event, $thread, $username);
0 ignored issues
show
Security Bug introduced by
It seems like $username defined by $this->activityManager->getSecurityUsername() on line 60 can also be of type false; however, Graviton\AuditTrackingBu...reManager::trackEvent() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
76
        }
77
    }
78
79
    /**
80
     * Save the event to DB
81
     *
82
     * @param AuditTracking $event    Performed by user
83
     * @param string        $thread   The thread ID
84
     * @param string        $username User connected name
85
     * @return void
86
     */
87
    private function trackEvent($event, $thread, $username)
88
    {
89
        // Request information
90
        $event->setThread($thread);
91
        $event->setUsername($username);
92
93
        try {
94
            $this->documentManager->persist($event);
95
            $this->documentManager->flush($event);
96
        } catch (\Exception $e) {
97
            die(var_dump($e->getMessage()));
0 ignored issues
show
Security Debugging Code introduced by
var_dump($e->getMessage()); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
Coding Style Compatibility introduced by
The method trackEvent() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
98
            // TODO LOG the error and event
99
        }
100
    }
101
102
103
104
    /**
105
     * Generate a unique identifer
106
     *
107
     * @return string
108
     */
109
    private function generateUUID()
110
    {
111
        if (!function_exists('openssl_random_pseudo_bytes')) {
112
            return uniqid('unq', true);
113
        }
114
115
        $data = openssl_random_pseudo_bytes(16);
116
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);    // set version to 0100
117
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);    // set bits 6-7 to 10
118
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
119
    }
120
}
121