Completed
Push — feature/EVO-7278-tracking-info... ( 70565f...ea41d2 )
by
unknown
08:58
created

StoreManager::persistEvents()   C

Complexity

Conditions 12
Paths 29

Size

Total Lines 50
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
dl 0
loc 50
ccs 0
cts 38
cp 0
rs 5.3904
c 0
b 0
f 0
cc 12
eloc 27
nc 29
nop 1
crap 156

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 Graviton\SecurityBundle\Entities\SecurityUser;
11
use Graviton\SecurityBundle\Service\SecurityUtils;
12
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
13
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
14
use Symfony\Bridge\Monolog\Logger;
15
16
/**
17
 * Class StoreManager
18
 * @package Graviton\AuditTrackingBundle\Manager
19
 *
20
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
21
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
22
 * @link     http://swisscom.ch
23
 */
24
class StoreManager
25
{
26
    const AUDIT_HEADER_KEY = 'x-header-audit-thread';
27
28
    /** @var ActivityManager */
29
    private $activityManager;
30
31
    /** @var Logger */
32
    private $logger;
33
34
    /** @var DocumentManager */
35
    private $documentManager;
36
    
37
    /** @var SecurityUtils */
38
    private $securityUtils;
39
40
    /**
41
     * StoreManager constructor.
42
     * @param ActivityManager $activityManager Main activity manager
43
     * @param Logger          $logger          Monolog log service
44
     * @param ManagerRegistry $doctrine        Doctrine document mapper
45
     * @param SecurityUtils   $securityUtils   Sf Auth token storage
46
     */
47
    public function __construct(
48
        ActivityManager $activityManager,
49
        Logger $logger,
50
        ManagerRegistry $doctrine,
51
        SecurityUtils $securityUtils
52
    ) {
53
        $this->activityManager = $activityManager;
54
        $this->logger = $logger;
55
        $this->documentManager = $doctrine->getManager();
56
        $this->securityUtils = $securityUtils;
57
    }
58
59
    /**
60
     * Save data to DB
61
     * onKernelResponse
62
     *
63
     * @param FilterResponseEvent $event Sf fired kernel event
64
     *
65
     * @return void
66
     */
67
    public function persistEvents(FilterResponseEvent $event)
68
    {
69
        // No events or no user.
70
        if (!($events = $this->activityManager->getEvents())) {
71
            $this->logger->debug('AuditTracking:exit-no-events');
72
            return;
73
        }
74
75
        // No events or no user.
76
        if (!$this->securityUtils->isSecurityUser()) {
77
            $this->logger->debug('AuditTracking:exit-no-user');
78
            return;
79
        }
80
81
        // Check if we wanna log test calls
82
        if (!$this->activityManager->getConfigValue('log_test_calls', 'bool')) {
83
            if (!$this->securityUtils->isSecurityUser()
84
                || !$this->securityUtils->hasRole(SecurityUser::ROLE_CONSULTANT)) {
85
                $this->logger->debug('AuditTracking:exit-no-real-user');
86
                return;
87
            }
88
        }
89
90
        $thread = $this->securityUtils->getThreadId();
91
        $response = $event->getResponse();
92
        
93
        // If request is valid we save it or we do not depending on the exceptions exclude policy
94
        if (!$this->activityManager->getConfigValue('log_on_failure', 'bool')) {
95
            $excludedStatus = $this->activityManager->getConfigValue('exceptions_exclude', 'array');
96
            if (!$response->isSuccessful()
97
                && !in_array($response->getStatusCode(), $excludedStatus)) {
98
                $this->logger->debug('AuditTracking:exit-on-failure:'.$thread.':'.json_encode($events));
99
                return;
100
            }
101
        }
102
103
        $username = $this->securityUtils->getSecurityUsername();
104
105
        $saved = false;
106
        foreach ($events as $event) {
107
            if (!($saved = $this->trackEvent($event, $thread, $username))) {
108
                break;
109
            }
110
        }
111
112
        // Set Audit header information
113
        if ($saved) {
114
            $response->headers->set(self::AUDIT_HEADER_KEY, $thread);
115
        }
116
    }
117
118
    /**
119
     * Save the event to DB
120
     *
121
     * @param AuditTracking $event    Performed by user
122
     * @param string        $thread   The thread ID
123
     * @param string        $username User connected name
124
     * @return bool
125
     */
126
    private function trackEvent($event, $thread, $username)
0 ignored issues
show
Coding Style introduced by
function trackEvent() does not seem to conform to the naming convention (^(?:is|has|should|may|supports)).

This check examines a number of code elements and verifies that they conform to the given naming conventions.

You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.

Loading history...
127
    {
128
        // Request information
129
        $event->setThread($thread);
130
        $event->setUsername($username);
131
        $saved = true;
132
133
        try {
134
            $this->documentManager->persist($event);
135
            $this->documentManager->flush($event);
136
        } catch (\Exception $e) {
137
            $this->logger->error('AuditTracking:persist-error:'.$thread.':'.json_encode($event));
138
            $saved = false;
139
        }
140
141
        return $saved;
142
    }
143
}
144