1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mdiyakov\DoctrineSolrBundle\Manager; |
4
|
|
|
|
5
|
|
|
use Doctrine\Bundle\DoctrineBundle\Registry; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
|
8
|
|
|
class EntityManager |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var IndexProcessManager |
12
|
|
|
*/ |
13
|
|
|
private $indexProcessManager; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var Registry |
17
|
|
|
*/ |
18
|
|
|
private $registry; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param IndexProcessManager $indexProcessManager |
22
|
|
|
* @param Registry $registry |
23
|
|
|
*/ |
24
|
|
|
public function __construct( |
25
|
|
|
IndexProcessManager $indexProcessManager, |
26
|
|
|
Registry $registry |
27
|
|
|
) { |
28
|
|
|
$this->indexProcessManager = $indexProcessManager; |
29
|
|
|
$this->registry = $registry; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param object $entity |
34
|
|
|
* @throws \Doctrine\ORM\ORMException |
35
|
|
|
* @throws \InvalidArgumentException |
36
|
|
|
* @throws \LogicException |
37
|
|
|
* @throws \Exception |
38
|
|
|
*/ |
39
|
|
|
public function flush($entity) |
40
|
|
|
{ |
41
|
|
|
if (!is_object($entity)) { |
42
|
|
|
throw new \InvalidArgumentException('Entity must be an object'); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if (!method_exists($entity, 'getId')) { |
46
|
|
|
throw new \LogicException('Entity must have method "getId" to handle rollback'); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** @var \Doctrine\ORM\EntityManager $em */ |
50
|
|
|
$em = $this->getEm($entity); |
51
|
|
|
try { |
52
|
|
|
$em->persist($entity); |
53
|
|
|
$em->flush($entity); |
54
|
|
|
} catch (\Exception $e) { |
55
|
|
|
if (!$em->isOpen()) { |
56
|
|
|
$em = $em->create( |
57
|
|
|
$em->getConnection(), $em->getConfiguration() |
58
|
|
|
); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$previousEntity = $em->getRepository(get_class($entity))->find($entity->getId()); |
62
|
|
|
if ($previousEntity) { |
63
|
|
|
$this->indexProcessManager->reindex($previousEntity); |
64
|
|
|
} else { |
65
|
|
|
$this->indexProcessManager->remove($entity); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
throw $e; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param object $entity |
74
|
|
|
* @throws \InvalidArgumentException |
75
|
|
|
* @return EntityManagerInterface |
76
|
|
|
*/ |
77
|
|
|
private function getEm($entity) |
78
|
|
|
{ |
79
|
|
|
$em = $this->registry->getManagerForClass(get_class($entity)); |
80
|
|
|
if (!$em) { |
81
|
|
|
throw new \InvalidArgumentException( |
82
|
|
|
sprintf('There is no entity manager for "%s" class', get_class($entity)) |
83
|
|
|
); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
if (!$em instanceof EntityManagerInterface) { |
87
|
|
|
throw new \InvalidArgumentException( |
88
|
|
|
'Entity manager must be instance of "EntityManagerInterface" class' |
89
|
|
|
); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return $em; |
93
|
|
|
} |
94
|
|
|
} |