DeviceController::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 4
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Alpha\VisitorTrackingBundle\Controller;
6
7
use Alpha\VisitorTrackingBundle\Entity\Device;
8
use Alpha\VisitorTrackingBundle\Entity\Session;
9
use Alpha\VisitorTrackingBundle\Manager\DeviceFingerprintManager;
10
use Alpha\VisitorTrackingBundle\Storage\SessionStore;
11
use Doctrine\ORM\EntityManager;
12
use Psr\Log\LoggerInterface;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
16
class DeviceController
17
{
18
    private $entityManager;
19
20
    private $logger;
21
22
    private $sessionStore;
23
24
    private $deviceFingerprintManager;
25
26
    public function __construct(
27
        EntityManager $entityManager,
28
        LoggerInterface $logger,
29
        SessionStore $sessionStore,
30
        DeviceFingerprintManager $deviceFingerprintManager
31
    ) {
32
        $this->entityManager = $entityManager;
33
        $this->logger = $logger;
34
        $this->sessionStore = $sessionStore;
35
        $this->deviceFingerprintManager = $deviceFingerprintManager;
36
    }
37
38
    public function fingerprintAction(Request $request): Response
39
    {
40
        $session = $this->sessionStore->getSession();
41
        $device = null;
42
43
        if ($session instanceof Session) {
44
            if ($session->getDevices()->count() > 0) {
45
                $device = $session->getDevices()->first();
46
            }
47
        }
48
49
        if (!$device instanceof Device) {
50
            $device = new Device();
51
            $device->setFingerprint((string) $request->getContent());
52
            $device->setSession($session);
53
54
            $this->deviceFingerprintManager->generateHashes($device);
55
56
            $this->entityManager->persist($device);
57
            $this->entityManager->flush($device);
58
59
            $this->logger->debug(\sprintf('A new device fingerprint was added with the id %d.', $device->getId()));
60
61
            return new Response('', 201);
62
        }
63
64
        return new Response('', 204);
65
    }
66
}
67