Completed
Push — master ( a199f7...eac768 )
by Oleg
06:42
created

HistoryManagement::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlowServer\Authorization\Service;
5
6
use Doctrine\ORM\UnitOfWork;
7
use SlayerBirden\DataFlowServer\Authorization\Entities\History;
8
use SlayerBirden\DataFlowServer\Authorization\Entities\Permission;
9
use SlayerBirden\DataFlowServer\Authorization\HistoryManagementInterface;
10
use SlayerBirden\DataFlowServer\Doctrine\Persistence\EntityManagerRegistry;
11
12
final class HistoryManagement implements HistoryManagementInterface
13
{
14
    const ACTION_ADD = 'added';
15
    const ACTION_REMOVE = 'removed';
16
    const ACTION_UNKNOWN = 'unknown';
17
    /**
18
     * @var EntityManagerRegistry
19
     */
20
    private $managerRegistry;
21
22 10
    public function __construct(EntityManagerRegistry $managerRegistry)
23
    {
24 10
        $this->managerRegistry = $managerRegistry;
25 10
    }
26
27
    /**
28
     * @param Permission $permission
29
     * @return History
30
     * @throws \Doctrine\ORM\ORMException
31
     */
32 4
    public function fromPermission(Permission $permission): History
33
    {
34 4
        $em = $this->managerRegistry->getManagerForClass(Permission::class);
35 4
        $state = $em->getUnitOfWork()->getEntityState($permission);
36
37
        switch ($state) {
38 4
            case UnitOfWork::STATE_MANAGED:
39 4
                $action = self::ACTION_ADD;
40 4
                break;
41 2
            case UnitOfWork::STATE_REMOVED:
42 2
                $action = self::ACTION_REMOVE;
43 2
                break;
44
            default:
45
                $action = self::ACTION_UNKNOWN;
46
        }
47
48 4
        $history = new History();
49 4
        $history->setChangeAction($action);
50 4
        $history->setPermission($permission);
51 4
        $history->setResource($permission->getResource());
52 4
        $history->setUser($permission->getUser());
53 4
        $history->setAt(new \DateTime());
54
55 4
        return $history;
56
    }
57
}
58