Completed
Push — master ( be772b...99d542 )
by Tomas
16:16
created

CachedUserManager   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B getPermissions() 0 20 5
A invalidatePermissions() 0 5 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Eziat\PermissionBundle\Manager;
6
7
use Eziat\PermissionBundle\Model\UserManagerAbstract;
8
use Eziat\PermissionBundle\Model\UserManagerInterface;
9
use Eziat\PermissionBundle\Model\UserPermissionInterface;
10
use Eziat\PermissionBundle\Utils\CacheHelperInterface;
11
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
12
13
/**
14
 * @author Tomas Jakl <[email protected]>
15
 */
16
class CachedUserManager extends UserManagerAbstract implements UserManagerInterface
17
{
18
    /**
19
     * @var CacheHelperInterface
20
     */
21
    private $cacheHelper;
22
23
    /**
24
     * @var string
25
     */
26
    private $cachePrefix;
27
28
    public function __construct(CacheHelperInterface $cacheHelper, TokenStorageInterface $tokenStorage, string $cachePrefix )
29
    {
30
        parent::__construct($tokenStorage);
31
        $this->cacheHelper = $cacheHelper;
32
        $this->cachePrefix = $cachePrefix;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function getPermissions(UserPermissionInterface $user = null) : array
39
    {
40
        $permissions = [];
41
        $user        = $user !== null ?: $this->getLoggedInUser();
42
43
        if ($user === null) {
44
            return $permissions;
45
        }
46
47
        $cacheID = $this->cachePrefix.$user->getId();
48
        $permissions = $this->cacheHelper->get($cacheID);
49
        if ($permissions === null) {
50
            $permissions = $this->getUserPermissions($user);
51
            if ( $permissions !== [] ){
52
                $this->cacheHelper->save($cacheID, $permissions);
53
            }
54
        }
55
56
        return $permissions;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function invalidatePermissions(UserPermissionInterface $user) : void
63
    {
64
        $cacheID = $this->cachePrefix.$user->getId();
65
        $this->cacheHelper->delete($cacheID);
66
    }
67
}