CustomerRegistrationFormSubscriber::preSubmit()   B
last analyzed

Complexity

Conditions 6
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 8.9457
c 0
b 0
f 0
nc 4
cc 6
nop 1
1
<?php
2
3
/*
4
 * This file is part of AppName.
5
 *
6
 * (c) Monofony
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 App\Form\EventSubscriber;
13
14
use App\Entity\Customer\CustomerInterface;
15
use Sylius\Component\Resource\Repository\RepositoryInterface;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\Form\Exception\UnexpectedTypeException;
18
use Symfony\Component\Form\FormEvent;
19
use Symfony\Component\Form\FormEvents;
20
21
final class CustomerRegistrationFormSubscriber implements EventSubscriberInterface
22
{
23
    /**
24
     * @var RepositoryInterface
25
     */
26
    private $customerRepository;
27
28
    /**
29
     * @param RepositoryInterface $customerRepository
30
     */
31
    public function __construct(RepositoryInterface $customerRepository)
32
    {
33
        $this->customerRepository = $customerRepository;
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public static function getSubscribedEvents()
40
    {
41
        return [
42
            FormEvents::PRE_SUBMIT => 'preSubmit',
43
        ];
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function preSubmit(FormEvent $event): void
50
    {
51
        $rawData = $event->getData();
52
        $form = $event->getForm();
53
        $data = $form->getData();
54
55
        if (!$data instanceof CustomerInterface) {
56
            throw new UnexpectedTypeException($data, CustomerInterface::class);
57
        }
58
59
        // if email is not filled in, go on
60
        if (!isset($rawData['email']) || empty($rawData['email'])) {
61
            return;
62
        }
63
        $existingCustomer = $this->customerRepository->findOneBy(['email' => $rawData['email']]);
64
        if (null === $existingCustomer || null !== $existingCustomer->getUser()) {
65
            return;
66
        }
67
68
        $existingCustomer->setUser($data->getUser());
69
        $form->setData($existingCustomer);
70
    }
71
}
72