|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace TemplateNamespace\Entity\Savers; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
|
6
|
|
|
use Doctrine\ORM\UnitOfWork; |
|
7
|
|
|
use Ramsey\Uuid\UuidInterface; |
|
8
|
|
|
use TemplateNamespace\Entities\TemplateEntity; |
|
9
|
|
|
use TemplateNamespace\Entity\DataTransferObjects\TemplateEntityDto; |
|
10
|
|
|
use TemplateNamespace\Entity\Interfaces\TemplateEntityInterface; |
|
11
|
|
|
|
|
12
|
|
|
class TemplateEntityUnitOfWorkHelper |
|
13
|
|
|
{ |
|
14
|
|
|
public const ENTITY_FQN = TemplateEntity::class; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @var UnitOfWork |
|
18
|
|
|
*/ |
|
19
|
|
|
private $unitOfWork; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(EntityManagerInterface $entityManager) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->unitOfWork = $entityManager->getUnitOfWork(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function getEntityFromUnitOfWorkUsingDto(TemplateEntityDto $dto): TemplateEntityInterface |
|
27
|
|
|
{ |
|
28
|
|
|
$uuid = $dto->getId(); |
|
29
|
|
|
if (false === ($uuid instanceof UuidInterface)) { |
|
30
|
|
|
throw new \RuntimeException('Unsupported ID type:' . print_r($uuid, true)); |
|
31
|
|
|
} |
|
32
|
|
|
if ($this->hasEntityByUuid($uuid)) { |
|
33
|
|
|
return $this->getEntityByUuid($uuid); |
|
34
|
|
|
} |
|
35
|
|
|
throw new \RuntimeException('Failed getting Entity from Unit of Work for ID ' . (string)$uuid); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function hasEntityByUuid(UuidInterface $uuid): bool |
|
39
|
|
|
{ |
|
40
|
|
|
$map = $this->unitOfWork->getIdentityMap(); |
|
41
|
|
|
|
|
42
|
|
|
return isset($map[self::ENTITY_FQN][(string)$uuid]); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function getEntityByUuid(UuidInterface $uuid): TemplateEntityInterface |
|
46
|
|
|
{ |
|
47
|
|
|
$map = $this->getIdentityMapForEntity(); |
|
48
|
|
|
$uuidString = (string)$uuid; |
|
49
|
|
|
if (isset($map[$uuidString]) && ($map[$uuidString] instanceof TemplateEntityInterface)) { |
|
50
|
|
|
return $map[$uuidString]; |
|
51
|
|
|
} |
|
52
|
|
|
throw new \RuntimeException('Failed finding Entity in Unit of Work'); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
public function getIdentityMapForEntity(): array |
|
56
|
|
|
{ |
|
57
|
|
|
$map = $this->unitOfWork->getIdentityMap(); |
|
58
|
|
|
if (false === isset($map[self::ENTITY_FQN])) { |
|
59
|
|
|
throw new \RuntimeException('No Identities in the Unit of Work for this Entity FQN'); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return $map[self::ENTITY_FQN]; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function hasRecordOfDto(TemplateEntityDto $dto): bool |
|
66
|
|
|
{ |
|
67
|
|
|
return $this->hasEntityByUuid($dto->getId()); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
} |
|
71
|
|
|
|