Completed
Push — master ( 1f454c...9af5c7 )
by Michał
22s
created

AddUserFormSubscriber::preSetData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 10
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
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\CoreBundle\Form\EventSubscriber;
13
14
use Sylius\Component\User\Model\UserAwareInterface;
15
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
16
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
17
use Symfony\Component\Form\FormEvent;
18
use Symfony\Component\Form\FormEvents;
19
use Symfony\Component\Validator\Constraints\Valid;
20
use Webmozart\Assert\Assert;
21
22
/**
23
 * @author Łukasz Chruściel <[email protected]>
24
 * @author Anna Walasek <[email protected]>
25
 */
26
final class AddUserFormSubscriber implements EventSubscriberInterface
27
{
28
    /**
29
     * @var string
30
     */
31
    private $entryType;
32
33
    /**
34
     * @param string $entryType
35
     */
36
    public function __construct($entryType)
37
    {
38
        $this->entryType = $entryType;
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public static function getSubscribedEvents()
45
    {
46
        return [
47
            FormEvents::PRE_SET_DATA => 'preSetData',
48
            FormEvents::SUBMIT => 'submit',
49
        ];
50
    }
51
52
    /**
53
     * @param FormEvent $event
54
     */
55
    public function preSetData(FormEvent $event)
56
    {
57
        $form = $event->getForm();
58
        $form->add('user', $this->entryType, ['constraints' => [new Valid()]]);
59
        $form->add('createUser', CheckboxType::class, [
60
            'label' => 'sylius.ui.customer_can_login_to_the_store',
61
            'required' => false,
62
            'mapped' => false,
63
        ]);
64
    }
65
66
    /**
67
     * @param FormEvent $event
68
     */
69
    public function submit(FormEvent $event)
70
    {
71
        $data = $event->getData();
72
        $form = $event->getForm();
73
74
        if(null === $form->get('createUser')->getViewData()) {
75
76
            Assert::isInstanceOf($data, UserAwareInterface::class);
77
78
            $data->setUser(null);
79
            $event->setData($data);
80
81
            $form->remove('user');
82
            $form->add('user', $this->entryType, ['constraints' => [new Valid()]]);
83
        }
84
    }
85
}
86