1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Sylius package. |
5
|
|
|
* |
6
|
|
|
* (c) Paweł Jędrzejewski |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Sylius\Bundle\UserBundle\Form\EventSubscriber; |
13
|
|
|
|
14
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
15
|
|
|
use Symfony\Component\Form\FormEvent; |
16
|
|
|
use Symfony\Component\Form\FormEvents; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @author Łukasz Chruściel <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class AddUserFormSubscriber implements EventSubscriberInterface |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
|
|
public static function getSubscribedEvents() |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
|
|
FormEvents::PRE_SET_DATA => 'preSetData', |
30
|
|
|
FormEvents::PRE_SUBMIT => 'preSubmit', |
31
|
|
|
]; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param FormEvent $event |
36
|
|
|
*/ |
37
|
|
|
public function preSetData(FormEvent $event) |
38
|
|
|
{ |
39
|
|
|
$form = $event->getForm(); |
40
|
|
|
$form->add('user', 'sylius_user'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @param FormEvent $event |
45
|
|
|
*/ |
46
|
|
|
public function preSubmit(FormEvent $event) |
47
|
|
|
{ |
48
|
|
|
$data = $event->getData(); |
49
|
|
|
|
50
|
|
|
if (!isset($data['user'])) { |
51
|
|
|
$this->removeUserField($event); |
52
|
|
|
|
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if ($this->isUserDataEmpty($data)) { |
57
|
|
|
unset($data['user']); |
58
|
|
|
$event->setData($data); |
59
|
|
|
$this->removeUserField($event); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* @param array $data |
65
|
|
|
* |
66
|
|
|
* @return bool |
67
|
|
|
*/ |
68
|
|
|
private function isUserDataEmpty(array $data) |
69
|
|
|
{ |
70
|
|
|
foreach ($data['user'] as $field) { |
71
|
|
|
if (!empty($field)) { |
72
|
|
|
return false; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return true; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @param FormEvent $event |
81
|
|
|
*/ |
82
|
|
|
private function removeUserField(FormEvent $event) |
83
|
|
|
{ |
84
|
|
|
$form = $event->getForm(); |
85
|
|
|
$form->remove('user'); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|