AddUserFormSubscriber::preSetData()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace App\Form\EventSubscriber;
4
5
use Sylius\Component\User\Model\UserAwareInterface;
6
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
8
use Symfony\Component\Form\FormEvent;
9
use Symfony\Component\Form\FormEvents;
10
use Symfony\Component\Validator\Constraints\Valid;
11
use Webmozart\Assert\Assert;
12
13
final class AddUserFormSubscriber implements EventSubscriberInterface
14
{
15
    /**
16
     * @var string
17
     */
18
    private $entryType;
19
20
    /**
21
     * @param string $entryType
22
     */
23
    public function __construct($entryType)
24
    {
25
        $this->entryType = $entryType;
26
    }
27
28
    /**
29
     * @return array
30
     */
31
    public static function getSubscribedEvents()
32
    {
33
        return [
34
            FormEvents::PRE_SET_DATA => 'preSetData',
35
            FormEvents::SUBMIT => 'submit',
36
        ];
37
    }
38
39
    /**
40
     * @param FormEvent $event
41
     */
42
    public function preSetData(FormEvent $event): void
43
    {
44
        $form = $event->getForm();
45
        $form->add('user', $this->entryType, ['constraints' => [new Valid()]]);
46
        $form->add('createUser', CheckboxType::class, [
47
            'label' => 'app.ui.create_user',
48
            'required' => false,
49
            'mapped' => false,
50
        ]);
51
    }
52
53
    /**
54
     * @param FormEvent $event
55
     */
56
    public function submit(FormEvent $event): void
57
    {
58
        $data = $event->getData();
59
        $form = $event->getForm();
60
61
        /* @var UserAwareInterface $data */
62
        Assert::isInstanceOf($data, UserAwareInterface::class);
63
64
        if (null === $data->getUser()->getId() && null === $form->get('createUser')->getViewData()) {
65
            $data->setUser(null);
66
            $event->setData($data);
67
68
            $form->remove('user');
69
            $form->add('user', $this->entryType, ['constraints' => [new Valid()]]);
70
        }
71
    }
72
}
73