|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Gvera\Commands; |
|
4
|
|
|
|
|
5
|
|
|
use Gvera\Exceptions\NotFoundException; |
|
6
|
|
|
use Gvera\Helpers\entities\GvEntityManager; |
|
7
|
|
|
use Gvera\Models\UserRole; |
|
8
|
|
|
use Gvera\Models\UserRoleAction; |
|
9
|
|
|
|
|
10
|
|
|
class CreateOrAssignUserRoleActionCommand implements CommandInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var string |
|
14
|
|
|
*/ |
|
15
|
|
|
private $actionName; |
|
16
|
|
|
/** |
|
17
|
|
|
* @var string |
|
18
|
|
|
*/ |
|
19
|
|
|
private $userRoleName; |
|
20
|
|
|
/** |
|
21
|
|
|
* @var GvEntityManager |
|
22
|
|
|
*/ |
|
23
|
|
|
private $entityManager; |
|
24
|
|
|
|
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* CreateOrAssignUserRoleActionCommand constructor. |
|
28
|
|
|
* @param string $actionName |
|
29
|
|
|
* @param string $userRoleName |
|
30
|
|
|
* @param GvEntityManager $entityManager |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __construct(string $actionName, string $userRoleName, GvEntityManager $entityManager) |
|
|
|
|
|
|
33
|
|
|
{ |
|
34
|
|
|
$this->actionName = $actionName; |
|
35
|
|
|
$this->userRoleName = $userRoleName; |
|
36
|
|
|
$this->entityManager = $entityManager; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @throws NotFoundException |
|
41
|
|
|
* @throws \Doctrine\ORM\ORMException |
|
42
|
|
|
* @throws \Doctrine\ORM\OptimisticLockException |
|
43
|
|
|
*/ |
|
44
|
|
|
public function execute():void |
|
45
|
|
|
{ |
|
46
|
|
|
$exists = $this->entityManager->getRepository(UserRoleAction::class) |
|
47
|
|
|
->findOneBy(['name' => $this->actionName]); |
|
48
|
|
|
$action = $exists ?? new UserRoleAction(); |
|
49
|
|
|
$action->setActionName($this->actionName); |
|
50
|
|
|
|
|
51
|
|
|
$userRole = $this->entityManager->getRepository(UserRole::class) |
|
|
|
|
|
|
52
|
|
|
->findOneBy(['name' => $this->userRoleName]); |
|
53
|
|
|
|
|
54
|
|
|
if (null === $userRole) { |
|
55
|
|
|
throw new NotFoundException('user role was not found', ['userRoleName' => $this->userRoleName]); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
$action->addUserRole($userRole); |
|
59
|
|
|
$this->entityManager->persist($action); |
|
60
|
|
|
$this->entityManager->flush(); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|
The
EntityManagermight become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:If that code throws an exception and the
EntityManageris closed. Any other code which depends on the same instance of theEntityManagerduring this request will fail.On the other hand, if you instead inject the
ManagerRegistry, thegetManager()method guarantees that you will always get a usable manager instance.