-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
MergeCollectionListener.php
72 lines (60 loc) · 1.99 KB
/
MergeCollectionListener.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\AdminBundle\Form\EventListener;
use Sonata\AdminBundle\Model\ModelManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
/**
* @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
*/
final class MergeCollectionListener implements EventSubscriberInterface
{
/**
* @var ModelManagerInterface
*/
private $modelManager;
public function __construct(ModelManagerInterface $modelManager)
{
$this->modelManager = $modelManager;
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::SUBMIT => ['onBind', 10],
];
}
public function onBind(FormEvent $event): void
{
$collection = $event->getForm()->getData();
$data = $event->getData();
// looks like there is no way to remove other listeners
$event->stopPropagation();
if (!$collection) {
$collection = $data;
} elseif (0 === \count($data)) {
$this->modelManager->collectionClear($collection);
} else {
// merge $data into $collection
foreach ($collection as $model) {
if (!$this->modelManager->collectionHasElement($data, $model)) {
$this->modelManager->collectionRemoveElement($collection, $model);
} else {
$this->modelManager->collectionRemoveElement($data, $model);
}
}
foreach ($data as $model) {
$this->modelManager->collectionAddElement($collection, $model);
}
}
$event->setData($collection);
}
}