1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Custom Model Document Version listener |
4
|
|
|
*/ |
5
|
|
|
|
6
|
|
|
namespace Graviton\DocumentBundle\Listener; |
7
|
|
|
|
8
|
|
|
use Graviton\RestBundle\Event\ModelEvent; |
9
|
|
|
use Doctrine\ODM\MongoDB\DocumentManager; |
10
|
|
|
use Graviton\SchemaBundle\Constraint\VersionFieldConstraint; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class DocumentVersionListener |
14
|
|
|
* @package Graviton\DocumentBundle\Listener |
15
|
|
|
* |
16
|
|
|
* @author List of contributors <https://github.com/libgraviton/graviton/graphs/contributors> |
17
|
|
|
* @license http://opensource.org/licenses/gpl-license.php GNU Public License |
18
|
|
|
* @link http://swisscom.ch |
19
|
|
|
*/ |
20
|
|
|
class DocumentVersionListener |
21
|
|
|
{ |
22
|
|
|
/** @var DocumentManager Document manager */ |
23
|
|
|
private $documentManager; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* constructor. |
27
|
|
|
* @param DocumentManager $documentManager Db Connection document manager |
28
|
|
|
*/ |
29
|
|
|
public function __construct(DocumentManager $documentManager) |
30
|
|
|
{ |
31
|
|
|
$this->documentManager = $documentManager; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Updating a Model |
36
|
|
|
* @param ModelEvent $event Mongo.odm event argument |
37
|
|
|
* @return void |
38
|
|
|
*/ |
39
|
|
|
public function modelUpdate(ModelEvent $event) |
40
|
|
|
{ |
41
|
|
|
$this->updateCounter($event, 'update'); |
42
|
|
|
} |
43
|
|
|
/** |
44
|
|
|
* Insert a Model |
45
|
|
|
* @param ModelEvent $event Mongo.odm event argument |
46
|
|
|
* @return void |
47
|
|
|
*/ |
48
|
|
|
public function modelInsert(ModelEvent $event) |
49
|
|
|
{ |
50
|
|
|
$this->updateCounter($event, 'insert'); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Update Counter for all new saved items |
55
|
|
|
* |
56
|
|
|
* @param ModelEvent $event Object event |
57
|
|
|
* @param string $action What is to be done |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
|
|
private function updateCounter(ModelEvent $event, $action) |
61
|
|
|
{ |
62
|
|
|
if (!property_exists($event->getCollection(), VersionFieldConstraint::FIELD_NAME)) { |
63
|
|
|
return; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$qb = $this->documentManager->createQueryBuilder($event->getCollectionClass()); |
67
|
|
|
if ('update' == $action) { |
68
|
|
|
$qb->findAndUpdate() |
69
|
|
|
->field('id')->equals($event->getCollectionId()) |
70
|
|
|
->field(VersionFieldConstraint::FIELD_NAME)->inc(1) |
71
|
|
|
->getQuery()->execute(); |
72
|
|
|
} else { |
73
|
|
|
$qb->findAndUpdate() |
74
|
|
|
->field('id')->equals($event->getCollectionId()) |
75
|
|
|
->field(VersionFieldConstraint::FIELD_NAME)->set(1) |
76
|
|
|
->getQuery()->execute(); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|