|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace steevanb\DoctrineReadOnlyHydrator\EventSubscriber; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\Common\EventSubscriber; |
|
6
|
|
|
use Doctrine\Common\Persistence\Event\LifecycleEventArgs; |
|
7
|
|
|
use Doctrine\ORM\Event\PreFlushEventArgs; |
|
8
|
|
|
use Doctrine\ORM\Events; |
|
9
|
|
|
use steevanb\DoctrineReadOnlyHydrator\Entity\ReadOnlyEntityInterface; |
|
10
|
|
|
use steevanb\DoctrineReadOnlyHydrator\Exception\ReadOnlyEntityCantBeFlushedException; |
|
11
|
|
|
use steevanb\DoctrineReadOnlyHydrator\Exception\ReadOnlyEntityCantBePersistedException; |
|
12
|
|
|
|
|
13
|
|
|
class ReadOnlySubscriber implements EventSubscriber |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @return array |
|
17
|
|
|
*/ |
|
18
|
|
|
public function getSubscribedEvents() |
|
19
|
|
|
{ |
|
20
|
|
|
return array(Events::prePersist, Events::preFlush); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @param LifecycleEventArgs $args |
|
25
|
|
|
* @throws ReadOnlyEntityCantBePersistedException |
|
26
|
|
|
*/ |
|
27
|
|
|
public function prePersist(LifecycleEventArgs $args) |
|
28
|
|
|
{ |
|
29
|
|
|
if ($this->isReadOnlyEntity($args->getObject())) { |
|
30
|
|
|
throw new ReadOnlyEntityCantBePersistedException($args->getObject()); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param PreFlushEventArgs $args |
|
36
|
|
|
* @throws ReadOnlyEntityCantBeFlushedException |
|
37
|
|
|
*/ |
|
38
|
|
|
public function preFlush(PreFlushEventArgs $args) |
|
39
|
|
|
{ |
|
40
|
|
|
$unitOfWork = $args->getEntityManager()->getUnitOfWork(); |
|
41
|
|
|
$entities = array_merge( |
|
42
|
|
|
$unitOfWork->getScheduledEntityInsertions(), |
|
43
|
|
|
$unitOfWork->getScheduledEntityUpdates(), |
|
44
|
|
|
$unitOfWork->getScheduledEntityDeletions() |
|
45
|
|
|
); |
|
46
|
|
|
foreach ($entities as $entity) { |
|
47
|
|
|
if ($this->isReadOnlyEntity($entity)) { |
|
48
|
|
|
throw new ReadOnlyEntityCantBeFlushedException($entity); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param object $entity |
|
55
|
|
|
* @return bool |
|
56
|
|
|
*/ |
|
57
|
|
|
protected function isReadOnlyEntity($entity) |
|
58
|
|
|
{ |
|
59
|
|
|
return $entity instanceof ReadOnlyEntityInterface; |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|